#!/bin/bash
set -e

echo "========================================="
echo "君鸿卡管系统 API 服务启动中..."
echo "========================================="

# 构建数据库连接 URL（从环境变量读取）
# 环境变量由 docker-compose 传入，格式为 JUNHONG_DATABASE_*
DB_HOST="${JUNHONG_DATABASE_HOST:-localhost}"
DB_PORT="${JUNHONG_DATABASE_PORT:-5432}"
DB_USER="${JUNHONG_DATABASE_USER:-postgres}"
DB_PASSWORD="${JUNHONG_DATABASE_PASSWORD:-}"
DB_NAME="${JUNHONG_DATABASE_DBNAME:-junhong_cmp}"
DB_SSLMODE="${JUNHONG_DATABASE_SSLMODE:-disable}"

DB_URL="postgresql://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME}?sslmode=${DB_SSLMODE}"

echo "检查数据库连接..."
for i in {1..30}; do
    if migrate -path /app/migrations -database "$DB_URL" version > /dev/null 2>&1; then
        echo "数据库连接成功"
        break
    fi
    echo "等待数据库就绪... ($i/30)"
    sleep 1
done

echo "执行数据库迁移..."
if migrate -path /app/migrations -database "$DB_URL" up; then
    echo "数据库迁移完成"
else
    echo "警告: 数据库迁移失败或无新迁移"
fi

echo "启动 API 服务..."
echo "========================================="
exec /app/api
