@echo off
chcp 65001 >nul
REM ============================================
REM 数据库一键初始化脚本 (Windows)
REM 用法: 双击运行或在项目根目录执行 database\init.bat
REM ============================================

setlocal enabledelayedexpansion

REM 读取 .env.local 配置
set "ENV_FILE="
if exist "apps\server\.env.local" (
    set "ENV_FILE=apps\server\.env.local"
) else if exist "apps\server\.env" (
    set "ENV_FILE=apps\server\.env"
) else (
    echo 错误: 未找到 .env.local 或 .env 文件
    pause
    exit /b 1
)

REM 解析配置
for /f "usebackq tokens=1,* delims==" %%a in ("!ENV_FILE!") do (
    if "%%a"=="DB_HOST" set "DB_HOST=%%b"
    if "%%a"=="DB_PORT" set "DB_PORT=%%b"
    if "%%a"=="DB_USERNAME" set "DB_USER=%%b"
    if "%%a"=="DB_PASSWORD" set "DB_PASS=%%b"
    if "%%a"=="DB_DATABASE" set "DB_NAME=%%b"
)

echo ==========================================
echo   数据库初始化
echo ==========================================
echo 主机: %DB_HOST%:%DB_PORT%
echo 用户: %DB_USER%
echo 数据库: %DB_NAME%
echo ==========================================
echo.

REM 执行迁移
echo [1/2] 执行数据库迁移...
mysql -h %DB_HOST% -P %DB_PORT% -u %DB_USER% -p%DB_PASS% < database\migrations\001_init_schema.sql
if errorlevel 1 (
    echo   x 迁移失败，请检查 MySQL 连接配置
    pause
    exit /b 1
)
echo   √ 表结构创建完成
echo.

REM 执行种子数据
echo [2/2] 导入种子数据...
mysql -h %DB_HOST% -P %DB_PORT% -u %DB_USER% -p%DB_PASS% %DB_NAME% < database\seeds\001_init_data.sql
if errorlevel 1 (
    echo   x 种子数据导入失败
    pause
    exit /b 1
)
echo   √ 种子数据导入完成
echo.

echo ==========================================
echo   初始化完成!
echo ==========================================
pause
