#!/bin/bash

# PostgreSQL 数据库初始化脚本
# 此脚本在 PostgreSQL 容器首次启动时自动执行

set -e

echo "========================================="
echo "QAUP 数据库初始化开始"
echo "========================================="

# 创建数据库（如果不存在）
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
    -- 创建扩展
    CREATE EXTENSION IF NOT EXISTS postgis;
    CREATE EXTENSION IF NOT EXISTS postgis_topology;
    
    -- 显示扩展信息
    SELECT name, default_version, installed_version 
    FROM pg_available_extensions 
    WHERE name IN ('postgis', 'postgis_topology');
EOSQL

echo "✓ PostGIS 扩展安装完成"

# 导入数据库架构
if [ -f "/docker-entrypoint-initdb.d/qaup_database_schema.sql" ]; then
    echo "导入数据库架构..."
    psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" -f /docker-entrypoint-initdb.d/qaup_database_schema.sql
    echo "✓ 数据库架构导入完成"
else
    echo "警告: 未找到数据库架构文件"
fi

# 导入初始数据（按优先级顺序）
data_files=(
    "/docker-entrypoint-initdb.d/initial_data.sql"
    "/docker-entrypoint-initdb.d/01_system_data.sql"
    "/docker-entrypoint-initdb.d/02_business_data.sql"
    "/docker-entrypoint-initdb.d/03_sample_data.sql"
)

for data_file in "${data_files[@]}"; do
    if [ -f "$data_file" ]; then
        echo "导入数据文件: $(basename "$data_file")"
        psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" -f "$data_file"
        echo "✓ $(basename "$data_file") 导入完成"
        
        # 如果找到 initial_data.sql，就不再导入其他文件
        if [[ "$data_file" == *"initial_data.sql" ]]; then
            break
        fi
    fi
done

# 检查是否导入了任何数据
imported_any=false
for data_file in "${data_files[@]}"; do
    if [ -f "$data_file" ]; then
        imported_any=true
        break
    fi
done

if [ "$imported_any" = false ]; then
    echo "警告: 未找到初始数据文件，系统将使用空数据库启动"
    echo "建议从现有系统导出数据或使用默认初始数据"
fi

# 创建数据库用户和权限设置
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
    -- 创建应用用户（如果不存在）
    DO \$\$
    BEGIN
        IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = '${APP_DB_USER:-qaup_app}') THEN
            CREATE USER ${APP_DB_USER:-qaup_app} WITH PASSWORD '${APP_DB_PASSWORD:-qaup123}';
        END IF;
    END
    \$\$;
    
    -- 授予权限
    GRANT CONNECT ON DATABASE ${POSTGRES_DB} TO ${APP_DB_USER:-qaup_app};
    GRANT USAGE ON SCHEMA public TO ${APP_DB_USER:-qaup_app};
    GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO ${APP_DB_USER:-qaup_app};
    GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO ${APP_DB_USER:-qaup_app};
    
    -- 为未来创建的表设置默认权限
    ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO ${APP_DB_USER:-qaup_app};
    ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT USAGE, SELECT ON SEQUENCES TO ${APP_DB_USER:-qaup_app};
EOSQL

echo "✓ 数据库用户和权限设置完成"

# 显示数据库信息
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
    -- 显示数据库基本信息
    SELECT 
        current_database() as database_name,
        current_user as current_user,
        version() as postgresql_version;
    
    -- 显示表数量
    SELECT 
        schemaname,
        COUNT(*) as table_count
    FROM pg_tables 
    WHERE schemaname = 'public'
    GROUP BY schemaname;
EOSQL

echo ""
echo "========================================="
echo "QAUP 数据库初始化完成"
echo "========================================="