IMAGE_NAME = authentikate
CONTAINER_NAME = authentikate
PORT = 8889
VERSION = latest
TEST_PORT = 8890
TEST_CONTAINER_NAME = authentikate-test

# Default target
.DEFAULT_GOAL := help

# Make sure to get set up with octane and frankenPHP
# since that's what the base docker image expects
setup: ## Install Laravel Octane with FrankenPHP
	composer require laravel/octane
	php artisan octane:install --server=frankenphp

# Docker build targets
build: ## Build the Docker image
	@echo "Building Docker image: $(IMAGE_NAME):$(VERSION)"
	npm run build
	docker build -t $(IMAGE_NAME):$(VERSION) .
	@echo "✅ Image built successfully"

build-no-cache: ## Build the Docker image without cache
	@echo "Building Docker image without cache: $(IMAGE_NAME):$(VERSION)"
	docker build --no-cache -t $(IMAGE_NAME):$(VERSION) .
	@echo "✅ Image built successfully"

# Run targets
run: ## Run the container (production-like)
	@echo "Starting container: $(CONTAINER_NAME)"
	@docker stop $(CONTAINER_NAME) 2>/dev/null || true
	@docker rm $(CONTAINER_NAME) 2>/dev/null || true
	docker run -d \
		--name $(CONTAINER_NAME) \
		-p $(PORT):8000 \
		-e APP_NAME="AuthentiKate" \
		-e APP_ENV=production \
		-e APP_DEBUG=true \
		-e APP_KEY=base64:$$(openssl rand -base64 32) \
		-e APP_URL=http://localhost:$(PORT) \
		-e DB_CONNECTION=sqlite \
		-e DB_DATABASE=/app/database/database.sqlite \
		-v authentikate_keys:/app/storage/oauth \
		-v authentikate_db:/app/database \
		-v authentikate_storage:/app/storage \
		$(IMAGE_NAME):$(VERSION)
	@echo "✅ Container started on http://localhost:$(PORT)"
	@echo "📋 Check logs with: make logs"
	@echo "🔑 Admin credentials will be shown in the logs"

run-test: ## Run a test container with different settings
	@echo "Starting test container: $(TEST_CONTAINER_NAME)"
	@docker stop $(TEST_CONTAINER_NAME) 2>/dev/null || true
	@docker rm $(TEST_CONTAINER_NAME) 2>/dev/null || true
	docker run -d \
		--name $(TEST_CONTAINER_NAME) \
		-p $(TEST_PORT):8000 \
		-e APP_NAME="AuthentiKate Test" \
		-e APP_ENV=testing \
		-e APP_DEBUG=true \
		-e APP_KEY=base64:$$(openssl rand -base64 32) \
		-e APP_URL=http://localhost:$(TEST_PORT) \
		-e DB_CONNECTION=sqlite \
		-e DB_DATABASE=/app/database/test.sqlite \
		-v authentikate_test_keys:/app/storage/oauth \
		-v authentikate_test_db:/app/database \
		-v authentikate_test_storage:/app/storage \
		$(IMAGE_NAME):$(VERSION)
	@echo "✅ Test container started on http://localhost:$(TEST_PORT)"
	@echo "📋 Check logs with: make logs-test"

run-interactive: ## Run container interactively for debugging
	@echo "Starting interactive container"
	@docker stop $(CONTAINER_NAME)-debug 2>/dev/null || true
	@docker rm $(CONTAINER_NAME)-debug 2>/dev/null || true
	docker run -it --rm \
		--name $(CONTAINER_NAME)-debug \
		-p $(PORT):8000 \
		-e APP_ENV=local \
		-e APP_DEBUG=true \
		-e APP_KEY=base64:$$(openssl rand -base64 32) \
		-e APP_URL=http://localhost:$(PORT) \
		-e DB_CONNECTION=sqlite \
		-e DB_DATABASE=/app/database/debug.sqlite \
		$(IMAGE_NAME):$(VERSION) \
		/bin/bash

# Container management
stop: ## Stop the running container
	@echo "Stopping container: $(CONTAINER_NAME)"
	@docker stop $(CONTAINER_NAME) 2>/dev/null || echo "Container not running"
	@docker rm $(CONTAINER_NAME) 2>/dev/null || echo "Container already removed"

stop-test: ## Stop the test container
	@echo "Stopping test container: $(TEST_CONTAINER_NAME)"
	@docker stop $(TEST_CONTAINER_NAME) 2>/dev/null || echo "Container not running"
	@docker rm $(TEST_CONTAINER_NAME) 2>/dev/null || echo "Container already removed"

stop-all: ## Stop all containers
	@echo "Stopping all containers"
	@docker stop $(CONTAINER_NAME) $(TEST_CONTAINER_NAME) 2>/dev/null || true
	@docker rm $(CONTAINER_NAME) $(TEST_CONTAINER_NAME) 2>/dev/null || true

restart: stop run ## Restart the container

restart-test: stop-test run-test ## Restart the test container

# Logs and debugging
logs: ## Show container logs
	docker logs -f $(CONTAINER_NAME)

logs-test: ## Show test container logs
	docker logs -f $(TEST_CONTAINER_NAME)

logs-tail: ## Show last 50 lines of container logs
	docker logs --tail 50 $(CONTAINER_NAME)

shell: ## Open a shell in the running container
	docker exec -it $(CONTAINER_NAME) /bin/bash

shell-test: ## Open a shell in the test container
	docker exec -it $(TEST_CONTAINER_NAME) /bin/bash

# Full workflow targets
rebuild: build stop run ## Rebuild image and restart container

rebuild-test: build stop-test run-test ## Rebuild image and restart test container

rebuild-no-cache: build-no-cache stop run ## Rebuild without cache and restart

test-full: build run-test ## Build and run test container
	@echo "⏳ Waiting for container to start..."
	@sleep 10
	@echo "🧪 Running health check..."
	@curl -f http://localhost:$(TEST_PORT) >/dev/null 2>&1 && echo "✅ Health check passed" || echo "❌ Health check failed"
	@echo "📋 Test container logs:"
	@docker logs $(TEST_CONTAINER_NAME) | tail -20

# Cleanup targets
clean: ## Remove containers and images
	@echo "Cleaning up containers and images"
	@docker stop $(CONTAINER_NAME) $(TEST_CONTAINER_NAME) 2>/dev/null || true
	@docker rm $(CONTAINER_NAME) $(TEST_CONTAINER_NAME) 2>/dev/null || true
	@docker rmi $(IMAGE_NAME):$(VERSION) 2>/dev/null || echo "Image not found"

clean-volumes: ## Remove all volumes (WARNING: destroys data)
	@echo "⚠️  WARNING: This will destroy all data in volumes!"
	@read -p "Are you sure? (y/N) " -n 1 -r; \
	if [[ $$REPLY =~ ^[Yy]$$ ]]; then \
		echo; \
		docker volume rm authentikate_keys authentikate_db authentikate_storage 2>/dev/null || true; \
		docker volume rm authentikate_test_keys authentikate_test_db authentikate_test_storage 2>/dev/null || true; \
		echo "✅ Volumes removed"; \
	else \
		echo; \
		echo "❌ Cancelled"; \
	fi

clean-all: clean clean-volumes ## Remove everything (containers, images, volumes)

# Development targets
dev-build-test: ## Quick development build and test cycle
	@echo "🔄 Development build and test cycle"
	@make build
	@make run-test
	@echo "⏳ Waiting for container to start..."
	@sleep 5
	@make logs-tail
	@echo "🌐 Test instance available at: http://localhost:$(TEST_PORT)"

# Status and info
status: ## Show container status
	@echo "=== Container Status ==="
	@docker ps -a --filter name=$(CONTAINER_NAME) --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
	@docker ps -a --filter name=$(TEST_CONTAINER_NAME) --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
	@echo
	@echo "=== Volume Status ==="
	@docker volume ls --filter name=authentikate

info: ## Show image and container information
	@echo "=== Image Information ==="
	@docker images $(IMAGE_NAME):$(VERSION) --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}\t{{.CreatedAt}}"
	@echo
	@echo "=== Container Information ==="
	@docker inspect $(CONTAINER_NAME) 2>/dev/null | grep -E '"IPAddress"|"Ports"' || echo "Container not running"

urls: ## Show accessible URLs
	@echo "=== Available URLs ==="
	@echo "Production: http://localhost:$(PORT)"
	@echo "Test:       http://localhost:$(TEST_PORT)"
	@echo "Health:     http://localhost:$(PORT)/up"

# Help target
help: ## Show this help message
	@echo "AuthentiKate Docker Makefile"
	@echo "============================="
	@echo
	@echo "Usage: make [target]"
	@echo
	@echo "Targets:"
	@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf "  %-20s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
	@echo
	@echo "Quick Start:"
	@echo "  make build run    # Build and run production container"
	@echo "  make dev-build-test  # Quick dev cycle"
	@echo "  make logs         # View logs"
	@echo "  make clean        # Clean up"