#!/bin/bash
# OCDP Backend - Production 模式快速启动脚本

set -e

echo "🚀 OCDP Backend - Production 模式快速启动"
echo "========================================="
echo ""

# 检查 Docker
if ! command -v docker &> /dev/null; then
    echo "❌ Docker 未安装，请先安装 Docker"
    exit 1
fi

# 检查 docker compose
if ! docker compose version &> /dev/null; then
    echo "❌ docker compose 未安装，请先安装 Docker Compose V2"
    exit 1
fi

echo "✅ Docker 环境检查通过"
echo ""

# 获取项目根目录
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_ROOT="$( cd "$SCRIPT_DIR/../.." && pwd )"

# 启动 PostgreSQL（从根目录）
echo "📦 启动 PostgreSQL..."
cd "$PROJECT_ROOT"
docker compose up -d postgres

echo "⏳ 等待 PostgreSQL 就绪..."
sleep 5

# 检查 PostgreSQL 是否就绪
docker compose exec -T postgres pg_isready -U postgres || {
    echo "❌ PostgreSQL 启动失败"
    exit 1
}

# 返回 backend 目录
cd "$PROJECT_ROOT/backend"

echo "✅ PostgreSQL 已就绪"
echo ""

# 设置环境变量
export ADAPTER_MODE=production
export DATABASE_URL="postgres://postgres:postgres@localhost:5432/ocdp?sslmode=disable"
export ENCRYPTION_KEY="default-encryption-key-change-me-32"
export JWT_SECRET="your-jwt-secret-key-change-in-production"
export PORT=8080

echo "🔧 环境配置:"
echo "  - ADAPTER_MODE: $ADAPTER_MODE"
echo "  - DATABASE_URL: $DATABASE_URL"
echo "  - PORT: $PORT"
echo ""

# 编译
echo "🔨 编译应用..."
go build -o bin/ocdp-backend cmd/api/main.go

echo "✅ 编译完成"
echo ""

# 启动应用
echo "🚀 启动 OCDP Backend (Production 模式)..."
echo ""
echo "📍 服务地址:"
echo "  - API: http://localhost:8080/api/v1"
echo "  - Health: http://localhost:8080/health"
echo ""
echo "📍 数据库管理:"
echo "  - pgAdmin: http://localhost:5050"
echo "    Email: ${PGADMIN_EMAIL:-admin@ocdp.local}"
echo "    Password: ${PGADMIN_PASSWORD:-change-me}"
echo ""
echo "✨ 按 Ctrl+C 停止服务"
echo ""

./bin/ocdp-backend
