ENV_FILE := --env-file apps/backend/.env
DEV      := docker compose $(ENV_FILE)
PROD     := docker compose $(ENV_FILE) -f docker-compose.prod.yml

.DEFAULT_GOAL := help

.PHONY: help
help: ## Show this help
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | \
		awk 'BEGIN {FS = ":.*?## "}; {printf "  \033[36m%-14s\033[0m %s\n", $$1, $$2}'

.PHONY: init
init: ## Copy backend env file (run once)
	@[ -f apps/backend/.env ] || cp apps/backend/.env.example apps/backend/.env
	@echo "Environment ready: apps/backend/.env"

.PHONY: dev
dev: ## Start the development stack (foreground)
	$(DEV) up

.PHONY: dev-d
dev-d: ## Start the development stack (detached)
	$(DEV) up -d

.PHONY: build
build: ## Build development images
	$(DEV) build

.PHONY: down
down: ## Stop the development stack
	$(DEV) down

.PHONY: logs
logs: ## Tail development logs
	$(DEV) logs -f

.PHONY: sh-backend
sh-backend: ## Shell into the backend container
	$(DEV) exec backend sh

.PHONY: sh-frontend
sh-frontend: ## Shell into the frontend container
	$(DEV) exec frontend sh

.PHONY: migrate
migrate: ## Run database migrations
	$(DEV) exec backend php artisan migrate

.PHONY: seed
seed: ## Seed the database
	$(DEV) exec backend php artisan db:seed

.PHONY: fresh
fresh: ## Drop, re-migrate and seed the database
	$(DEV) exec backend php artisan migrate:fresh --seed

.PHONY: key
key: ## Generate the Laravel application key
	$(DEV) exec backend php artisan key:generate

.PHONY: prod-build
prod-build: ## Build production images
	$(PROD) build

.PHONY: prod-up
prod-up: ## Start the production stack (detached)
	$(PROD) up -d

.PHONY: prod-down
prod-down: ## Stop the production stack
	$(PROD) down
