#!/bin/bash
# 将已导出的基础数据 SQL 导入目标库
#
# 用法：
#   TARGET_DSN="postgres://user:pass@host:5432/db?sslmode=disable" \
#   bash scripts/manual_db_release/04_import_base_data_into_target.sh
#
# 如需导入敏感表：
#   TARGET_DSN="..." INCLUDE_SENSITIVE=1 bash scripts/manual_db_release/04_import_base_data_into_target.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
GENERATED_DIR="${SCRIPT_DIR}/generated"
NON_SENSITIVE_DIR="${GENERATED_DIR}/non_sensitive"
SENSITIVE_DIR="${GENERATED_DIR}/sensitive"

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

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

import_order=(
    "tb_permission"
    "tb_role"
    "tb_role_permission"
    "tb_carrier"
    "tb_commission_withdrawal_setting"
    "tb_polling_config"
    "tb_polling_concurrency_config"
    "tb_polling_alert_rule"
    "tb_data_cleanup_config"
)

echo "开始导入非敏感基础数据..."
for table_name in "${import_order[@]}"; do
    sql_file="${NON_SENSITIVE_DIR}/${table_name}.sql"
    if [ ! -f "${sql_file}" ]; then
        echo "错误：缺少导出文件 ${sql_file}"
        echo "请先执行 03_export_base_data_from_source.sh"
        exit 1
    fi

    echo "  导入: ${table_name}"
    psql "${TARGET_DSN}" -v ON_ERROR_STOP=1 -f "${sql_file}"
done

if [ "${INCLUDE_SENSITIVE:-0}" = "1" ]; then
    sensitive_file="${SENSITIVE_DIR}/tb_wechat_config.sql"
    if [ ! -f "${sensitive_file}" ]; then
        echo "错误：缺少敏感导出文件 ${sensitive_file}"
        echo "请先使用 INCLUDE_SENSITIVE=1 执行 03_export_base_data_from_source.sh"
        exit 1
    fi

    echo "  导入: tb_wechat_config"
    psql "${TARGET_DSN}" -v ON_ERROR_STOP=1 -f "${sensitive_file}"
else
    echo "未导入敏感表。若需导入 tb_wechat_config，请设置 INCLUDE_SENSITIVE=1。"
fi

echo ""
echo "基础数据导入完成。"
echo "下一步请执行："
echo "  1. scripts/manual_db_release/05_repair_base_data_sequences.sql"
echo "  2. scripts/manual_db_release/06_mark_schema_migrations.sql"
