.PHONY: help setup start stop clean logs shell-backend shell-frontend migrate create-admin rebuild traefik-dashboard traefik-logs service-discovery network-inspect health-check-all mobile-setup db-shell-app install type-check lint build-local

help:
	@echo "MotoVaultPro - Simplified 5-Container Architecture"
	@echo "Commands:"
	@echo "  make setup         - Initial project setup (K8s-ready environment)"
	@echo "  make start         - Start all services (production mode)"
	@echo "  make rebuild       - Rebuild and restart containers (production)"
	@echo "  make stop          - Stop all services"
	@echo "  make clean         - Clean all data and volumes"
	@echo "  make logs          - View logs from all services"
	@echo "  make logs-backend  - View backend logs only"
	@echo "  make logs-frontend - View frontend logs only"
	@echo "  make shell-backend - Open shell in backend container"
	@echo "  make shell-frontend - Open shell in frontend container"
	@echo "  make migrate       - Run database migrations"
	@echo "  make create-admin  - Create initial admin user (fresh deployments only)"
	@echo ""
	@echo "K8s-Ready Architecture Commands:"
	@echo "  make traefik-dashboard - Access Traefik service discovery dashboard"
	@echo "  make traefik-logs      - View Traefik access and error logs"
	@echo "  make service-discovery - Show discovered services and routes"
	@echo "  make network-inspect   - Inspect 4-tier network topology"
	@echo "  make health-check-all  - Check health of all services"
	@echo "  make mobile-setup      - Setup instructions for mobile testing"
	@echo ""
	@echo "Database Access (Container-Only):"
	@echo "  make db-shell-app      - Application database shell"
	@echo ""
	@echo "Local Development (No Docker):"
	@echo "  make install       - Install npm dependencies locally"
	@echo "  make type-check    - Run TypeScript type checks"
	@echo "  make lint          - Run ESLint on all code"
	@echo "  make build-local   - Build frontend and backend locally"

setup:
	@echo "Setting up MotoVaultPro K8s-ready development environment..."
	@echo "1. Checking if .env file exists..."
	@if [ ! -f .env ]; then \
		echo "WARNING: .env file not found. Using defaults for development."; \
		echo "Create .env file for custom configuration."; \
	fi
	@echo "2. Checking SSL certificates..."
	@if [ ! -f certs/motovaultpro.com.crt ]; then \
		echo "Generating multi-domain SSL certificate..."; \
		$(MAKE) generate-certs; \
	fi
	@echo "3. Building and starting all containers with 3-tier network isolation..."
	@docker compose up -d --build --remove-orphans
	@echo "4. Running database migrations..."
	@sleep 15  # Wait for databases to be ready
	@docker compose exec mvp-backend node dist/_system/migrations/run-all.js
	@echo ""
	@echo "K8s-ready setup complete!"
	@echo "Access application at: https://motovaultpro.com"
		@echo "Traefik dashboard at: https://motovaultpro.com:8080"
	@echo ""
	@echo "Network Architecture:"
	@echo "  - 3-tier isolation: frontend, backend, database"
	@echo "  - All traffic routed through Traefik (no direct service access)"
	@echo "  - Development database access: ports 5432, 6379"
	@echo ""
	@echo "Mobile setup: make mobile-setup"

start:
	@echo "Starting application services..."
	@docker compose up -d --build --remove-orphans
	@echo "Application running!"

stop:
	@docker compose down

clean:
	@echo "Cleaning up all containers, volumes, and images..."
	@docker compose down -v --rmi all
	@docker system prune -f

logs:
	@docker compose logs -f

logs-backend:
	@docker compose logs -f mvp-backend

logs-frontend:
	@docker compose logs -f mvp-frontend

shell-backend:
	@docker compose exec mvp-backend sh

shell-frontend:
	@docker compose exec mvp-frontend sh

migrate:
	@echo "Running application database migrations..."
	@docker compose exec mvp-backend node dist/_system/migrations/run-all.js
	@echo "Migrations completed."

create-admin:
	@echo ""
	@echo "Creating initial admin user..."
	@echo "This command is only for fresh deployments with no existing admins."
	@echo ""
	@docker compose exec -it mvp-backend node dist/_system/cli/create-admin.js

rebuild:
	@echo "Rebuilding containers with latest code changes..."
	@docker compose up -d --build --remove-orphans
	@echo "Containers rebuilt and restarted!"

# Database Shell Access (K8s-equivalent: kubectl exec)
db-shell-app:
	@echo "Opening application database shell..."
	@docker compose exec mvp-postgres psql -U postgres -d motovaultpro

# K8s-Ready Architecture Commands
traefik-dashboard:
	@echo "Traefik Service Discovery Dashboard:"
		@echo "  Dashboard: https://motovaultpro.com:8080"
		@echo "  API: https://motovaultpro.com:8080/api"
	@echo ""
	@echo "Available routes:"
		@curl -ks https://motovaultpro.com:8080/api/http/routers 2>/dev/null | jq -r '.[].name' | grep -v internal | sed 's/^/  - /' || echo "  (Traefik not ready yet)"

traefik-logs:
	@echo "Traefik access and error logs:"
	@docker compose logs -f traefik


service-discovery:
	@echo "Service Discovery Status:"
	@echo ""
	@echo "Discovered Services:"
		@curl -ks https://motovaultpro.com:8080/api/http/services 2>/dev/null | jq -r '.[].name' | grep -v internal | sed 's/^/  - /' || echo "  Traefik not ready yet"
	@echo ""
	@echo "Active Routes:"
		@curl -ks https://motovaultpro.com:8080/api/http/routers 2>/dev/null | jq -r '.[].name' | grep -v internal | sed 's/^/  -> /' || echo "  No routes discovered yet"

network-inspect:
	@echo "K8s-Ready Network Architecture:"
	@echo ""
	@echo "Created Networks:"
	@docker network ls --filter name=motovaultpro --format "table {{.Name}}\t{{.Driver}}\t{{.Scope}}" | grep -v default || echo "Networks not created yet"
	@echo ""
	@echo "Network Isolation Details:"
	@echo "  - frontend    - Public-facing (Traefik + frontend services)"
	@echo "  - backend     - API services (internal isolation)"
	@echo "  - database    - Data persistence (internal isolation)"

health-check-all:
	@echo "Service Health Status:"
	@docker compose ps --format "table {{.Service}}\t{{.Status}}\t{{.Health}}"
	@echo ""
	@echo "Network Connectivity Test:"
		@echo "  Traefik API: $$(curl -ks -o /dev/null -w '%{http_code}' https://motovaultpro.com:8080/api/http/services 2>/dev/null || echo 'FAIL')"
	@echo ""
	@echo "Service Discovery Status:"
		@echo "  Discovered Services: $$(curl -ks https://motovaultpro.com:8080/api/http/services 2>/dev/null | jq '. | length' || echo '0')"
		@echo "  Active Routes: $$(curl -ks https://motovaultpro.com:8080/api/http/routers 2>/dev/null | jq '. | length' || echo '0')"

# SSL Certificate Generation
generate-certs:
	@echo "Generating multi-domain SSL certificate for mobile compatibility..."
	@mkdir -p certs
	@openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
		-keyout certs/motovaultpro.com.key \
		-out certs/motovaultpro.com.crt \
		-config <(echo '[dn]'; echo 'CN=motovaultpro.com'; echo '[req]'; echo 'distinguished_name = dn'; echo '[SAN]'; echo 'subjectAltName=DNS:motovaultpro.com,DNS:admin.motovaultpro.com,DNS:*.motovaultpro.com,IP:127.0.0.1,IP:172.30.1.64') \
		-extensions SAN
	@echo "Certificate generated with SAN for mobile compatibility (includes $(shell hostname -I | awk '{print $$1}'))"


# Enhanced log commands with filtering
logs-traefik:
	@docker compose logs -f traefik

logs-backend-full:
	@docker compose logs -f mvp-backend mvp-postgres mvp-redis

logs-clear:
	@sudo sh -c "truncate -s 0 /var/lib/docker/containers/**/*-json.log"

# Database Export/Import
db-export:
	@echo "Exporting database..."
	@./scripts/export-database.sh

db-export-schema:
	@echo "Exporting database schema only..."
	@./scripts/export-database.sh --schema-only --output schema_$(shell date +%Y%m%d)

db-export-custom:
	@echo "Exporting database (custom format)..."
	@./scripts/export-database.sh --format custom --output backup_$(shell date +%Y%m%d)

db-import:
	@echo "Import database from file"
	@echo "Usage: make db-import-file FILE=path/to/backup.sql.gz"
	@echo "Or use: ./scripts/import-database.sh --help"

db-import-file:
	@if [ -z "$(FILE)" ]; then \
		echo "Error: FILE parameter required"; \
		echo "Usage: make db-import-file FILE=database-exports/backup.sql.gz"; \
		exit 1; \
	fi
	@./scripts/import-database.sh $(FILE)

db-backup:
	@echo "Creating database backup..."
	@./scripts/export-database.sh --output backup_$(shell date +%Y%m%d_%H%M%S)

# =============================================================================
# Local Development (No Docker Required)
# =============================================================================
# Use these commands to quickly check for TypeScript errors and linting issues
# without rebuilding Docker containers.

.PHONY: install type-check lint build-local

install:
	@echo "Installing dependencies locally..."
	@cd frontend && npm install
	@cd backend && npm install
	@echo "Dependencies installed!"

type-check:
	@echo "Running TypeScript type checks..."
	@echo "Frontend:"
	@cd frontend && npm run type-check
	@echo ""
	@echo "Backend:"
	@cd backend && npm run type-check
	@echo ""
	@echo "Type checks complete!"

lint:
	@echo "Running linters..."
	@echo "Frontend:"
	@cd frontend && npm run lint
	@echo ""
	@echo "Backend:"
	@cd backend && npm run lint
	@echo ""
	@echo "Linting complete!"

build-local:
	@echo "Building frontend and backend locally..."
	@echo "Frontend:"
	@cd frontend && npm run build
	@echo ""
	@echo "Backend:"
	@cd backend && npm run build
	@echo ""
	@echo "Build complete! Check frontend/dist and backend/dist"
