.PHONY: dev dev-backend dev-frontend build test compose-up seed-demo \
        test-up test-down test-reset test-rebuild test-e2e

dev:
	@echo "Starting backend and frontend in parallel..."
	@make -j 2 dev-backend dev-frontend

dev-backend:
	cd backend && cargo run

dev-frontend:
	cd frontend && pnpm dev

lint:
	@echo "Running backend format check..."
	cd backend && cargo fmt --check
	@echo "Running backend clippy..."
	cd backend && cargo clippy -- -D warnings
	@echo "Running frontend type check..."
	cd frontend && pnpm check

build: lint
	cd frontend && pnpm build
	cd backend && cargo build --release

test: lint
	cd backend && cargo test

compose-up:
	docker-compose up --build

seed-demo:
	@mkdir -p data
	@echo "Applying migrations and seeding demo data..."
	@DB_PATH=$${DATABASE_URL:-sqlite:data/attendance.db}; \
	DB_FILE=$${DB_PATH#sqlite:}; \
	rm -f $$DB_FILE; \
	for f in backend/migrations/*.sql; do \
		echo "Applying $$f..."; \
		sqlite3 $$DB_FILE < $$f; \
	done; \
	sqlite3 $$DB_FILE < backend/demo/demo_seed.sql

# ── Test pipeline ─────────────────────────────────────────────────────────────

test-rebuild:
	@. scripts/test-env.sh; \
	mkdir -p data/test; \
	rm -f "$$TT_TEST_DB"; \
	echo "[test-rebuild] DB wiped at $$TT_TEST_DB"

test-up:
	@. scripts/test-env.sh; \
	if [ -f data/test/.pid ] && kill -0 $$(cat data/test/.pid) 2>/dev/null; then \
		echo "[test-up] Backend already running (PID $$(cat data/test/.pid)) on port $$TT_TEST_PORT"; \
		exit 0; \
	fi; \
	[ -f "$$TT_TEST_DB" ] || $(MAKE) test-rebuild; \
	DATABASE_URL="sqlite:$$TT_TEST_DB" PORT=$$TT_TEST_PORT TT_TEST_MODE=1 JWT_SECRET=testsecret STATIC_DIR=frontend/build \
		cargo run --manifest-path backend/Cargo.toml &>/tmp/tutortool-test.log & \
	echo $$! > data/test/.pid; \
	echo "[test-up] Backend PID $$(cat data/test/.pid) starting on port $$TT_TEST_PORT..."; \
	for i in $$(seq 1 30); do \
		curl -fs "$$TT_BASE_URL/health" >/dev/null 2>&1 && break; \
		sleep 1; \
	done; \
	curl -fs "$$TT_BASE_URL/health" >/dev/null 2>&1 || (echo "[test-up] Backend failed to start; see /tmp/tutortool-test.log" && exit 1); \
	$(MAKE) test-reset; \
	echo "[test-up] Backend ready on $$TT_BASE_URL"


test-down:
	@. scripts/test-env.sh; \
	if [ -f data/test/.pid ]; then \
		kill $$(cat data/test/.pid) 2>/dev/null || true; \
		rm -f data/test/.pid data/test/.port; \
		echo "[test-down] Backend stopped"; \
	else \
		echo "[test-down] No PID file found; nothing to stop"; \
	fi

test-reset:
	@. scripts/test-env.sh; \
	if curl -fs "$$TT_BASE_URL/health" >/dev/null 2>&1; then \
		curl -fsS -X POST "$$TT_BASE_URL/__test__/reset"; \
		echo "[test-reset] DB reset via endpoint"; \
	else \
		echo "[test-reset] Backend not running; rebuilding DB file instead"; \
		$(MAKE) test-rebuild; \
	fi

test-e2e:
	$(MAKE) test-up
	@. scripts/test-env.sh; cd frontend && pnpm test:e2e
