#!/bin/bash
# 生成生产首发 schema 基线（只读，不修改源库）
#
# 用法：
#   SOURCE_DSN="postgres://user:pass@host:5432/db?sslmode=disable" \
#   OUTPUT_SQL="/tmp/00_schema_baseline.sql" \
#   bash scripts/manual_db_release/02_generate_schema_baseline.sh
#
# 可选：
#   EXTRA_EXCLUDE_TABLES="table_a,table_b"
#
# 默认排除：
#   - schema_migrations
#   - tb_data_usage_record
#   - tb_card_replacement_record_legacy

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
OUTPUT_SQL="${OUTPUT_SQL:-${SCRIPT_DIR}/generated/00_schema_baseline.sql}"

if ! command -v pg_dump >/dev/null 2>&1; then
    echo "错误：未找到 pg_dump，请先安装 PostgreSQL 客户端工具。"
    exit 1
fi

if [ -z "${SOURCE_DSN:-}" ]; then
    echo "错误：必须设置 SOURCE_DSN。"
    exit 1
fi

mkdir -p "$(dirname "${OUTPUT_SQL}")"

exclude_tables=(
    "schema_migrations"
    "tb_data_usage_record"
    "tb_card_replacement_record_legacy"
)

if [ -n "${EXTRA_EXCLUDE_TABLES:-}" ]; then
    IFS=',' read -r -a extra_tables <<< "${EXTRA_EXCLUDE_TABLES}"
    for table_name in "${extra_tables[@]}"; do
        table_name="$(echo "${table_name}" | xargs)"
        if [ -n "${table_name}" ]; then
            exclude_tables+=("${table_name}")
        fi
    done
fi

pg_dump_args=(
    "--schema-only"
    "--no-owner"
    "--no-acl"
    "--quote-all-identifiers"
)

for table_name in "${exclude_tables[@]}"; do
    pg_dump_args+=("--exclude-table=${table_name}")
done

echo "开始生成 schema 基线：${OUTPUT_SQL}"
pg_dump "${pg_dump_args[@]}" "${SOURCE_DSN}" > "${OUTPUT_SQL}"

echo ""
echo "schema 基线生成完成。"
echo "默认已排除以下对象："
for table_name in "${exclude_tables[@]}"; do
    echo "  - ${table_name}"
done

echo ""
echo "建议你人工复核以下兼容保留表是否需要继续保留："
echo "  - tb_card_replacement_request"
echo "  - tb_number_card"
echo "  - tb_payment_merchant_setting"
echo "  - tb_dev_capability_config"
