@echo off
REM Apply database migration script
REM Usage: apply-migration.bat <migration_filename>

if "%1"=="" (
  echo ❌ Error: No migration file specified
  echo Usage: apply-migration.bat ^<migration_filename^>
  echo Example: apply-migration.bat 007_enhance_contact_messages.sql
  exit /b 1
)

set MIGRATION_FILE=%1

if not exist "backend\migrations\%MIGRATION_FILE%" (
  echo ❌ Migration file not found: backend\migrations\%MIGRATION_FILE%
  exit /b 1
)

echo Getting database pod name...
for /f "delims=" %%i in ('kubectl get pod -n my-apps -l app.kubernetes.io/component=db -o jsonpath^="{.items[0].metadata.name}"') do set DB_POD=%%i

if "%DB_POD%"=="" (
  echo ❌ Database pod not found
  exit /b 1
)

echo 📦 Database pod: %DB_POD%
echo 📝 Applying migration: %MIGRATION_FILE%...
echo.

REM Copy migration file to pod
kubectl cp backend/migrations/%MIGRATION_FILE% my-apps/%DB_POD%:/tmp/migration.sql

REM Execute migration
kubectl exec -n my-apps %DB_POD% -- psql -U brand_master_user -d brand_master_db -f /tmp/migration.sql

echo.
echo ✅ Migration %MIGRATION_FILE% applied successfully!
echo.
echo 🔄 Restarting backend pod to pick up changes...
kubectl delete pod -n my-apps -l app.kubernetes.io/component=backend

echo.
echo ✅ Done! Backend will restart with updated schema.
