#!/bin/bash
# 重置数据库到干净状态（仅用于开发/测试环境）
# 用途：将数据库从任意状态重置为全新的生产基线
# 警告：此操作会清空所有数据，不可恢复！

set -e

DB_NAME="${JUNHONG_DATABASE_DBNAME:-junhong_cmp}"
DB_HOST="${JUNHONG_DATABASE_HOST:-localhost}"
DB_PORT="${JUNHONG_DATABASE_PORT:-5432}"
DB_USER="${JUNHONG_DATABASE_USER:-postgres}"
DB_PASSWORD="${JUNHONG_DATABASE_PASSWORD:-}"

if [ -z "$DB_HOST" ] || [ -z "$DB_USER" ] || [ -z "$DB_NAME" ]; then
    echo "错误：必须设置以下环境变量："
    echo "  JUNHONG_DATABASE_HOST"
    echo "  JUNHONG_DATABASE_USER"
    echo "  JUNHONG_DATABASE_DBNAME"
    exit 1
fi

DB_DSN="postgres://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME}?sslmode=disable"
ADMIN_DSN="postgres://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/postgres?sslmode=disable"

# 检查 squash 基线文件是否存在（发布前必须生成，参见 migrations/README.md）
if [ ! -f "migrations/000114_squash_baseline.up.sql" ]; then
    echo "❌ 错误：migrations/000114_squash_baseline.up.sql 不存在！"
    echo ""
    echo "全新数据库需要 squash 基线文件才能通过 migrate up 建表。"
    echo "请参考 migrations/README.md 的「发布前必做」章节生成该文件。"
    exit 1
fi

echo "警告：即将清空数据库 ${DB_NAME}（${DB_HOST}:${DB_PORT}），5 秒后继续..."
echo "按 Ctrl+C 取消"
sleep 5

echo "正在删除数据库 ${DB_NAME}..."
PGPASSWORD="${DB_PASSWORD}" psql "${ADMIN_DSN}" -c "DROP DATABASE IF EXISTS ${DB_NAME};"

echo "正在创建数据库 ${DB_NAME}..."
PGPASSWORD="${DB_PASSWORD}" psql "${ADMIN_DSN}" -c "CREATE DATABASE ${DB_NAME};"

echo "正在执行数据库迁移..."
migrate -path migrations -database "${DB_DSN}" up

echo "数据库重置完成！"
echo "当前迁移状态："
migrate -path migrations -database "${DB_DSN}" version
