#!/bin/bash
# VI: Script migration database cho từng service riêng lẻ (Polyglot: Node/Prisma & .NET/EF Core)

set -e

SERVICE=$1
MODE=$2

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

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

echo "🔄 Chạy migrations cho $SERVICE..."

cd "$SERVICE_PATH"

# -----------------------------------------------------------------------------
# 1. Environment Setup (Common)
# -----------------------------------------------------------------------------

# VI: Load biến môi trường (hybrid pattern)
if [ -f "../../deployments/local/.env.local" ]; then
    set -a
    source ../../deployments/local/.env.local
    set +a
fi

if [ -f ".env.local" ]; then
    set -a
    source .env.local
    set +a
fi

# -----------------------------------------------------------------------------
# 2. Logic Selection (Node vs .NET)
# -----------------------------------------------------------------------------

# A. Node.js with Prisma
if [ -f "prisma/schema.prisma" ] || [ -f "package.json" ]; then
    echo "   📦 Detected Node.js/Prisma project"

    # VI: Kiểm tra DATABASE_URL (Prisma cần cái này)
    if [ -z "$DATABASE_URL" ]; then
        echo "⚠️  DATABASE_URL chưa được thiết lập."
        exit 1
    fi

    if [ "$MODE" = "dev" ]; then
        echo "📝 Chạy Prisma migrate dev..."
        pnpm prisma migrate dev
    elif [ "$MODE" = "deploy" ]; then
        echo "🚀 Chạy Prisma migrate deploy..."
        pnpm prisma migrate deploy
        pnpm prisma generate
    elif [ "$MODE" = "reset" ]; then
        echo "⚠️  CẢNH BÁO: Reset database!"
        read -p "Bạn có chắc chắn? (yes/no): " confirm
        if [ "$confirm" = "yes" ]; then
            pnpm prisma migrate reset --force
        fi
    else
        echo "❌ Mode không hợp lệ cho Node.js: dev, deploy, reset"
        exit 1
    fi

# B. .NET with Entity Framework Core
elif compgen -G "*.sln" > /dev/null || compgen -G "src/*.sln" > /dev/null || compgen -G "*.csproj" > /dev/null; then
    echo "   📦 Detected .NET/EF Core project"

    # Locate the Project (API or Infrastructure usually holds the DbContext, but we run commands against the executable or startup project)
    # Usually we run `dotnet ef` against the API project (startup) or Infrastructure (where DbContext is).
    # Best practice: Run against startup project (API) which has connection strings.
    
    STARTUP_PROJECT="."
    if [ -d "src" ]; then
        # Try to find API project
        API_PROJ=$(find src -name "*.API.csproj" | head -n 1)
        if [ -n "$API_PROJ" ]; then
             STARTUP_PROJECT="$API_PROJ"
        fi
    fi
    
    echo "   👉 Using startup project: $STARTUP_PROJECT"

    # Check for dotnet-ef tool
    if ! dotnet tool list -g | grep -q "dotnet-ef"; then
        echo "⚠️  dotnet-ef tool not found globally. Installing..."
        dotnet tool install --global dotnet-ef || true
    fi

    if [ "$MODE" = "dev" ]; then
        echo "📝 Creating new migration (dotnet ef migrations add)..."
        read -p "Enter migration name (e.g. AddUsersTable): " migr_name
        if [ -z "$migr_name" ]; then
            migr_name="Migration_$(date +%Y%m%d%H%M%S)"
        fi
        dotnet ef migrations add "$migr_name" --project "$STARTUP_PROJECT"
        
        echo "Do you want to apply it now? (y/n)"
        read -p "> " apply_now
        if [ "$apply_now" = "y" ]; then
            dotnet ef database update --project "$STARTUP_PROJECT"
        fi

    elif [ "$MODE" = "deploy" ]; then
        echo "🚀 Applying migrations (dotnet ef database update)..."
        dotnet ef database update --project "$STARTUP_PROJECT"

    elif [ "$MODE" = "reset" ]; then
        echo "⚠️  CẢNH BÁO: Drop database & Update!"
        read -p "Confirm? (yes/no): " confirm
        if [ "$confirm" = "yes" ]; then
             dotnet ef database drop --force --project "$STARTUP_PROJECT"
             dotnet ef database update --project "$STARTUP_PROJECT"
        fi
    else
        echo "❌ Mode invalid for .NET: dev, deploy, reset"
        exit 1
    fi

else
    echo "❌ Unknown project type (Environment not supported)"
    exit 1
fi

echo "✅ Migrations hoàn tất!"
