# ===============================
# LTI-API Makefile (Docker Setup)
# ===============================

APP_NAME := lti-api
COMPOSE := docker compose -f docker-compose.yaml
NETWORK := lti-network
ENV_FILE := .env.lti-api

include $(ENV_FILE)
export $(shell sed 's/=.*//' $(ENV_FILE))

MIGRATIONS_DIR := ./migrations
MIGRATE_IMAGE := migrate/migrate:v4.15.2
DB_URL := postgres://$(DB_USER):$(DB_PASSWORD)@lti-postgres:5432/$(DB_NAME)?sslmode=disable

# --- Docker ---
docker-local:
	@echo "🚀 Starting $(APP_NAME) with local PostgreSQL & Redis..."
	@$(COMPOSE) up --build -d

docker-down:
	@$(COMPOSE) down --remove-orphans

docker-nuke:
	@echo "💣 Removing all containers, images, and volumes..."
	@$(COMPOSE) down --rmi all --volumes --remove-orphans

# --- Database / Migration ---

wait-db:
	@echo "⏳ Waiting for database lti-postgres to be ready (inside Docker network)..."
	@$(COMPOSE) run --rm app sh -c 'until nc -z lti-postgres 5432; do echo "Waiting for DB..."; sleep 2; done; echo "✅ Database is ready!"'

migrate-up: wait-db
	@echo "⬆️  Running migrations..."
	@docker run --rm -v $(MIGRATIONS_DIR):/migrations --network $(NETWORK) \
		$(MIGRATE_IMAGE) -path=/migrations/ -database "$(DB_URL)" up

migrate-down: wait-db
	@echo "⬇️  Rolling back all migrations..."
	@docker run --rm -v $(MIGRATIONS_DIR):/migrations --network $(NETWORK) \
		$(MIGRATE_IMAGE) -path=/migrations/ -database "$(DB_URL)" down -all

seed:
	@echo "🌱 Running seed script..."
	@$(COMPOSE) run --rm app go run cmd/seed/main.go

psql:
	@docker exec -it lti-postgres psql -U $(DB_USER) -d $(DB_NAME)

logs:
	@$(COMPOSE) logs -f app

restart:
	@$(COMPOSE) restart

status:
	@$(COMPOSE) ps
