.PHONY: help install \
       prod-build prod-up prod-down prod-restart prod-logs prod-logs-server prod-ps prod-deploy \
       test-build test-up test-down test-restart test-logs test-logs-server test-ps test-deploy \
       gateway-up gateway-down gateway-reload \
       gitea-up gitea-down gitea-logs \
       init deploy clean

DOCKER_PROD = docker-compose -f deploy/docker/docker-compose.prod.yml
DOCKER_TEST = docker-compose -f deploy/docker/docker-compose.test.yml
DOCKER_GATEWAY = docker-compose -f deploy/docker/docker-compose.gateway.yml
DOCKER_GITEA = docker-compose -f deploy/docker/docker-compose.gitea.yml

help: ## 显示帮助信息
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | \
		awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-25s\033[0m %s\n", $$1, $$2}'

install: ## 安装依赖
	npm install -g pnpm
	pnpm install

# ===== 生产环境 =====
prod-build: ## 构建生产环境镜像
	$(DOCKER_PROD) build --parallel

prod-up: ## 启动生产环境
	$(DOCKER_PROD) up -d

prod-down: ## 停止生产环境
	$(DOCKER_PROD) down

prod-restart: ## 重启生产环境
	$(DOCKER_PROD) restart

prod-logs: ## 查看生产环境日志
	$(DOCKER_PROD) logs -f --tail=100

prod-logs-server: ## 查看生产环境后端日志
	$(DOCKER_PROD) logs -f --tail=100 server

prod-ps: ## 查看生产环境容器
	$(DOCKER_PROD) ps

prod-deploy: prod-down prod-build prod-up ## 完整部署生产环境
	@echo ""
	@echo "生产环境部署完成！"
	@echo "  API:            http://api.pinzhuhui.com"
	@echo "  官网:           http://www.pinzhuhui.com"
	@echo "  商家后台:       http://merchant.pinzhuhui.com"
	@echo "  平台后台:       http://platform-admin.pinzhuhui.com"

# ===== 测试环境 =====
test-build: ## 构建测试环境镜像
	$(DOCKER_TEST) build --parallel

test-up: ## 启动测试环境
	$(DOCKER_TEST) up -d

test-down: ## 停止测试环境
	$(DOCKER_TEST) down

test-restart: ## 重启测试环境
	$(DOCKER_TEST) restart

test-logs: ## 查看测试环境日志
	$(DOCKER_TEST) logs -f --tail=100

test-logs-server: ## 查看测试环境后端日志
	$(DOCKER_TEST) logs -f --tail=100 server

test-ps: ## 查看测试环境容器
	$(DOCKER_TEST) ps

test-deploy: test-down test-build test-up ## 完整部署测试环境
	@echo ""
	@echo "测试环境部署完成！"
	@echo "  API:            http://api-test.pinzhuhui.com"
	@echo "  官网:           http://test.pinzhuhui.com"
	@echo "  商家后台:       http://merchant-test.pinzhuhui.com"
	@echo "  平台后台:       http://platform-admin-test.pinzhuhui.com"

# ===== 网关 =====
gateway-up: ## 启动网关
	$(DOCKER_GATEWAY) up -d

gateway-down: ## 停止网关
	$(DOCKER_GATEWAY) down

gateway-reload: ## 重载网关配置
	docker exec rent-gateway nginx -s reload

# ===== 快捷命令 =====
init: gateway-up ## 首次初始化（启动网关 + 创建网络）
	@echo "网络已创建，网关已启动。"
	@echo "接下来运行 make prod-deploy 或 make test-deploy"

deploy: prod-deploy ## 别名：部署生产环境

clean: ## 清理所有容器、数据卷和悬空镜像
	$(DOCKER_PROD) down -v
	$(DOCKER_TEST) down -v
	$(DOCKER_GATEWAY) down
	$(DOCKER_GITEA) down
	docker image prune -f

# ===== Gitea =====
gitea-up: ## 启动 Gitea + Act Runner
	$(DOCKER_GITEA) up -d

gitea-down: ## 停止 Gitea + Act Runner
	$(DOCKER_GITEA) down

gitea-logs: ## 查看 Gitea 日志
	$(DOCKER_GITEA) logs -f --tail=100
