#!/bin/bash
# ============================================
# 数据库一键初始化脚本
# 用法: bash database/init.sh
# ============================================

set -e

# 从 .env.local 或 .env 读取配置
ENV_FILE=""
if [ -f "apps/server/.env.local" ]; then
  ENV_FILE="apps/server/.env.local"
elif [ -f "apps/server/.env" ]; then
  ENV_FILE="apps/server/.env"
else
  echo "错误: 未找到 .env.local 或 .env 文件"
  exit 1
fi

# 读取配置
DB_HOST=$(grep DB_HOST "$ENV_FILE" | cut -d '=' -f2 | tr -d ' ')
DB_PORT=$(grep DB_PORT "$ENV_FILE" | cut -d '=' -f2 | tr -d ' ')
DB_USER=$(grep DB_USERNAME "$ENV_FILE" | cut -d '=' -f2 | tr -d ' ')
DB_PASS=$(grep DB_PASSWORD "$ENV_FILE" | cut -d '=' -f2 | tr -d ' ')
DB_NAME=$(grep DB_DATABASE "$ENV_FILE" | cut -d '=' -f2 | tr -d ' ')

echo "=========================================="
echo "  数据库初始化"
echo "=========================================="
echo "主机: ${DB_HOST}:${DB_PORT}"
echo "用户: ${DB_USER}"
echo "数据库: ${DB_NAME}"
echo "=========================================="

# 执行迁移脚本
echo ""
echo "[1/2] 执行数据库迁移..."
mysql -h "${DB_HOST}" -P "${DB_PORT}" -u "${DB_USER}" -p"${DB_PASS}" < database/migrations/001_init_schema.sql
echo "  ✓ 表结构创建完成"

# 执行种子数据
echo ""
echo "[2/2] 导入种子数据..."
mysql -h "${DB_HOST}" -P "${DB_PORT}" -u "${DB_USER}" -p"${DB_PASS}" "${DB_NAME}" < database/seeds/001_init_data.sql
echo "  ✓ 种子数据导入完成"

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