#!/bin/bash
# EN: Database migration script for individual services
# VI: Script migration database cho từng service riêng lẻ

set -e

SERVICE=$1

# EN: Validate service name parameter
# VI: Xác thực tham số tên service
if [ -z "$SERVICE" ]; then
    echo "Usage: $0 <service-name> [dev|deploy] / Cách dùng: $0 <tên-service> [dev|deploy]"
    echo "Example: $0 iam-service dev / Ví dụ: $0 iam-service dev"
    echo "Example: $0 iam-service deploy / Ví dụ: $0 iam-service deploy"
    exit 1
fi

# EN: Check if service directory exists
# VI: Kiểm tra thư mục service có tồn tại không
if [ ! -d "services/$SERVICE" ]; then
    echo "❌ Service $SERVICE not found / Không tìm thấy service $SERVICE"
    exit 1
fi

echo "🔄 Running migrations for $SERVICE... / Chạy migrations cho $SERVICE..."

cd "services/$SERVICE"

# EN: Load environment variables (hybrid pattern)
# VI: Load biến môi trường (hybrid pattern)
# EN: 1. Load shared env (JWT secrets, Redis config)
# VI: 1. Load shared env (JWT secrets, Redis config)
if [ -f "../../deployments/local/.env.local" ]; then
    export $(grep -v '^#' ../../deployments/local/.env.local | xargs)
fi

# EN: 2. Load service-specific env (DATABASE_URL, PORT, etc.)
# VI: 2. Load service-specific env (DATABASE_URL, PORT, etc.)
if [ -f ".env.local" ]; then
    export $(grep -v '^#' .env.local | xargs)
fi

# EN: Check if DATABASE_URL is set
# VI: Kiểm tra DATABASE_URL có được thiết lập không
if [ -z "$DATABASE_URL" ]; then
    echo "⚠️  DATABASE_URL not set. Please check your .env.local files: / DATABASE_URL chưa được thiết lập. Vui lòng kiểm tra file .env.local:"
    echo "   - Shared config: ../../deployments/local/.env.local"
    echo "   - Service config: .env.local"
    echo "   For Neon: postgresql://user:pass@ep-xxx.region.neon.tech/dbname?sslmode=require&pgbouncer=true"
    exit 1
fi

if [ "$2" = "dev" ]; then
    echo "📝 Running development migration (creates new migration)..."
    pnpm prisma migrate dev
else
    echo "🚀 Running production migration (applies existing migrations)..."
    pnpm prisma migrate deploy
fi

echo "✅ Migrations completed!"
