# NexusCRM Makefile
# Provides common build and development commands

.PHONY: generate build verify-generated verify-autonumber lint test test-e2e-api test-e2e-api-report test-e2e-frontend-probe clean tidb-up tidb-down tidb-bootstrap setup setup-verify dev

# Default target
all: build

# Generate all code from system_tables.json (single source of truth) plus
# data-spec-driven generators (data-specs/*.md → backend/internal/**).
generate:
	@echo "🔄 Generating code from system_tables.json..."
	cd backend && go run ./cmd/codegen
	@echo "🔄 Generating autonumber seeds from data-specs/..."
	cd scripts/gen && go run ./autonumber_seeds.go \
		-spec ../../data-specs/2026-04-18-autonumber-v2-seed-public.md \
		-out ../../backend/internal/controlplane/packs/platform_config_autonumber_formats.go
	@echo "✅ Generation complete"

# Build all components
build: generate
	@echo "🔨 Building backend..."
	cd backend && go build ./...
	@echo "🔨 Type-checking frontend..."
	npm run lint
	@echo "✅ Build complete"

# Verify generated code is up-to-date (used in CI)
verify-generated:
	@echo "🔍 Verifying generated code is up-to-date..."
	cd backend && go run ./cmd/codegen
	cd scripts/gen && go run ./autonumber_seeds.go \
		-spec ../../data-specs/2026-04-18-autonumber-v2-seed-public.md \
		-out ../../backend/internal/controlplane/packs/platform_config_autonumber_formats.go
	@git diff --exit-code shared/pkg/constants/z_generated_tables.go || (echo "❌ z_generated_tables.go is out of sync" && exit 1)
	@git diff --exit-code shared/pkg/constants/z_generated_fields.go || (echo "❌ z_generated_fields.go is out of sync" && exit 1)
	@git diff --exit-code shared/pkg/models/z_generated.go || (echo "❌ models/z_generated.go is out of sync" && exit 1)
	@git diff --exit-code frontend/src/generated-schema.ts || (echo "❌ generated-schema.ts is out of sync" && exit 1)
	@git diff --exit-code backend/internal/controlplane/packs/platform_config_autonumber_formats.go || (echo "❌ platform_config_autonumber_formats.go is out of sync (run 'make generate')" && exit 1)
	@python3 scripts/verify-public-autonumber-generated.py
	@bash scripts/verify-autonumber-canonicalizer.sh
	@echo "✅ Generated files are up-to-date"

# Fixpack F16 — ensure autonumber.CanonicalizeTokenRefs stays the single
# owner of the canonical token-refs serialization used for hash drift
# detection. See scripts/verify-autonumber-canonicalizer.sh.
verify-autonumber:
	@bash scripts/verify-autonumber-canonicalizer.sh

# Run linting
lint:
	@echo "🔍 Linting..."
	cd backend && go vet ./...
	npm run lint
	@echo "✅ Lint complete"

# Run all tests (Unit + Integration)
test: test-unit test-integration

# Run E2E API tests
test-e2e:
	@echo "🧪 Running E2E API Tests..."
	cd tests/e2e-api && python3 runner.py --all
	@echo "✅ E2E Tests Complete"

# Generate test report from latest JSON report
e2e-report:
	@REPORT=$$(ls -t tests/e2e-api/report-*.json 2>/dev/null | head -1); \
	if [ -z "$$REPORT" ]; then \
		echo "No report found in tests/e2e-api/"; \
		exit 1; \
	fi; \
	echo "📊 Generating report from $$REPORT..."; \
	python3 tests/e2e-api/generate_report.py "$$REPORT"
	@echo "✅ Report generated"

# Run Unit Tests (Fast, mocked DB)
test-unit:
	@echo "🧪 Running Unit Tests..."
	cd backend && go test ./...
	@echo "✅ Unit Tests Complete"

# Run Integration Tests (Slow, requires DB)
test-integration:
	@echo "🧪 Running Integration Tests..."
	cd backend && go test -p 1 -tags=integration ./...
	@echo "✅ Integration Tests Complete"

# Start local TiDB for integration tests
tidb-up:
	@echo "🐳 Starting TiDB..."
	docker compose up -d
	@echo "⏳ Waiting for TiDB to accept connections..."
	@for i in $$(seq 1 30); do \
		nc -z 127.0.0.1 $${TIDB_PORT:-4000} 2>/dev/null && break; \
		echo "  attempt $$i/30..."; \
		sleep 2; \
	done
	@nc -z 127.0.0.1 $${TIDB_PORT:-4000} 2>/dev/null || \
		(echo "❌ TiDB failed to start" && exit 1)
	@echo "✅ TiDB is ready on port $${TIDB_PORT:-4000}"

# Stop local TiDB
tidb-down:
	@echo "🐳 Stopping TiDB..."
	docker compose down -v
	@echo "✅ TiDB stopped"

# Bootstrap DB schema against local TiDB
tidb-bootstrap:
	TIDB_HOST=127.0.0.1 TIDB_PORT=$${TIDB_PORT:-4000} TIDB_USER=root TIDB_PASSWORD= TIDB_DATABASE=nexuscrm \
		cd backend && go run ./cmd/setup_db



# Control Plane: apply all metadata, packs, indexes, and verify
setup:
	@echo "🔧 Running control plane: apply all..."
	cd backend && go run ./cmd/setup apply
	@echo "✅ Control plane apply complete"

# Control Plane: read-only verification
setup-verify:
	@echo "🔍 Running control plane: verify..."
	cd backend && go run ./cmd/setup verify
	@echo "✅ Verification complete"

# E2E API Tests: run the current stable API scenes through the shared runner flow.
# The script accepts both DB_* and TIDB_* connection variables:
#   DB_HOST / DB_PORT / DB_USERNAME / DB_PASSWORD / DB_DATABASE
#   or
#   TIDB_HOST / TIDB_PORT / TIDB_USER / TIDB_PASSWORD / TIDB_DATABASE
#
# Default behavior:
#   - builds and starts the backend locally
#   - connects to the configured DB
#   - runs gate-core scenes: demo,validation,contract,quote_line
#   - skips legacy seed setup
#   - exits 0 by default while the broader suite is still under repair
#
# Example using a shared TiDB Cloud database:
#   export DB_HOST=gateway01.us-east-1.prod.aws.tidbcloud.com
#   export DB_PORT=4000
#   export DB_USERNAME=...
#   export DB_PASSWORD=...
#   export DB_DATABASE=nexuscrm
#   export NEXUSCRM_PASSWORD=...
#   make test-e2e-api
test-e2e-api:
	@chmod +x scripts/run-e2e-api-tests.sh
	@./scripts/run-e2e-api-tests.sh

# E2E API Tests report only (no re-run, uses latest report file)
test-e2e-api-report:
	@echo "📊 E2E API Test Report"
	cd tests/e2e-api && python3 generate_report.py

# Frontend-aligned API probes: mirrors the current frontend's real request paths
# and payload shapes. Intended as a smoke gate for user-visible regressions.
#
# Run all probes:
#   FRONTEND_OPPORTUNITY_ID=006... make test-e2e-frontend-probe
#
# Run all probes including mutation flows:
#   FRONTEND_OPPORTUNITY_ID=006... INCLUDE_MUTATIONS=1 make test-e2e-frontend-probe
#
# Run a single probe:
#   FRONTEND_OPPORTUNITY_ID=006... CASE=FE-QTO-001 make test-e2e-frontend-probe
test-e2e-frontend-probe:
	@echo "🧪 Running frontend-aligned API probes..."
	cd tests/e2e-api && python3 frontend_case_probe.py $(if $(CASE),--case $(CASE),) $(if $(INCLUDE_MUTATIONS),--include-mutations,)

# E2E Scenario Tests: run multi-step scenario test suite
# Runs scenarios/ directory JSON files with sequential step execution and shared state
# Each scenario stops on first failure (fail-fast to avoid cascading errors)
#
# Run specific scenario:
#   SCENARIO=quote-to-order make test-e2e-scenario
#
# Run all scenarios:
#   make test-e2e-scenario
test-e2e-scenario:
	@echo "🔨 Building backend..."
	cd backend && go build -o /tmp/nexuscrm-server ./cmd/server/
	@echo "🚀 Starting backend..."
	nohup /tmp/nexuscrm-server > /tmp/nexuscrm.log 2>&1 & \
	echo "Backend PID: $$!" && sleep 8
	@echo "✅ Backend started"
	@echo "🧪 Running E2E Scenario Tests..."
	cd tests/e2e-api && python3 scenario_runner.py $(if $(SCENARIO),--scenario $(SCENARIO),)
	@echo "📊 Scenario report saved to tests/e2e-api/"


# Developer workflow: apply then start server
dev: setup
	@echo "🚀 Starting server..."
	cd backend && go run ./cmd/server

# Clean generated files (for fresh regeneration)
clean:
	@echo "🧹 Cleaning generated files..."
	rm -f shared/pkg/constants/z_generated_tables.go
	rm -f shared/pkg/constants/z_generated_fields.go
	rm -f shared/pkg/models/z_generated.go
	rm -f frontend/src/generated-schema.ts
	@echo "✅ Clean complete"

# Help
help:
	@echo "NexusCRM Makefile Commands:"
	@echo "  make generate          - Generate code from system_tables.json"
	@echo "  make build             - Generate and build all components"
	@echo "  make verify-generated  - Verify generated files are up-to-date (for CI)"
	@echo "  make verify-autonumber - Verify autonumber canonicalizer single-owner (F16)"
	@echo "  make lint              - Run linting"
	@echo "  make test              - Run all tests"
	@echo "  make test-unit         - Run unit tests only"
	@echo "  make test-integration  - Run integration tests (requires TiDB)"
	@echo "  make test-e2e-api     - Run the stable E2E API scenes against configured TiDB"
	@echo "  make test-e2e-api-report - Show latest E2E API test report"
	@echo "  make test-e2e-frontend-probe - Run frontend-aligned API smoke probes"
	@echo "  make test-e2e-scenario - Run E2E scenario tests (SCENARIO=xxx to filter)"
	@echo "  make tidb-up           - Start local TiDB via Docker"
	@echo "  make tidb-down         - Stop local TiDB"
	@echo "  make tidb-bootstrap    - Bootstrap DB schema on local TiDB"
	@echo "  make setup             - Run control plane: apply all metadata + packs"
	@echo "  make setup-verify      - Run control plane: verify readiness"
	@echo "  make dev               - Apply + start server (developer workflow)"
	@echo "  make clean             - Remove generated files"
