.PHONY: check-docker lint-back format-back lint-front typecheck-front test-back test-front check test migrate migration-rollback

check-docker:
	@command -v docker >/dev/null 2>&1 || { echo "Docker nie jest zainstalowany lub nie ma go w PATH." >&2; exit 1; }
	@docker compose version >/dev/null 2>&1 || { echo "Docker Compose nie jest dostępny przez polecenie 'docker compose'." >&2; exit 1; }

MIGRATION_RUNNER = zyrarbot.storage.adapters.postgres.migration_runner

define run_in_dev
@if docker compose ps --status running --services | grep -qx '$(1)'; then \
	docker compose exec -T $(1) $(2); \
else \
	docker compose run --build --rm $(1) $(3); \
fi
endef

lint-back: check-docker
	$(call run_in_dev,discord-bot,ruff check --fix .,ruff check --fix .)

format-back: check-docker
	$(call run_in_dev,discord-bot,ruff format .,ruff format .)

lint-front: check-docker
	$(call run_in_dev,frontend,npm run lint:fix,sh -c 'test -x node_modules/.bin/eslint || npm ci; npm run lint:fix')

typecheck-front: check-docker
	$(call run_in_dev,frontend,npm run typecheck,sh -c 'test -x node_modules/.bin/vue-tsc || npm ci; npm run typecheck')

test-back: check-docker
	$(call run_in_dev,discord-bot,pytest,pytest)

test-front: check-docker
	$(call run_in_dev,frontend,npm run smoke,sh -c 'test -x node_modules/.bin/eslint || npm ci; npm run smoke')

check: lint-back format-back lint-front typecheck-front

test: test-back test-front

migrate: check-docker
	docker compose run --build --rm discord-bot python -m $(MIGRATION_RUNNER) migrate

# Użyj np. `make migration-rollback TO=1`; domyślnie cofa wszystkie migracje.
TO ?= 0
migration-rollback: check-docker
	docker compose run --build --rm discord-bot python -m $(MIGRATION_RUNNER) rollback --to $(TO)
