#!/bin/bash
# Run Ledger Correctness Migrations
# Executes all migrations in order with error checking

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
MIGRATIONS_DIR="$PROJECT_ROOT/db/migrations"

# Load database URL from environment or use default
DATABASE_URL="${DATABASE_URL:-${1:-postgresql://user:password@localhost:5432/dbis}}"

echo "=== Running Ledger Correctness Migrations ==="
echo "Database: $DATABASE_URL"
echo "Migrations directory: $MIGRATIONS_DIR"
echo ""

# Check if migrations directory exists
if [ ! -d "$MIGRATIONS_DIR" ]; then
    echo "❌ Migrations directory not found: $MIGRATIONS_DIR"
    exit 1
fi

# List of migrations in order
MIGRATIONS=(
    "001_ledger_idempotency.sql"
    "002_dual_ledger_outbox.sql"
    "003_outbox_state_machine.sql"
    "004_balance_constraints.sql"
    "005_post_ledger_entry.sql"
)

# Function to check if migration was already applied
check_migration_applied() {
    local migration_name=$1
    # This assumes you have a migrations tracking table
    # Adjust based on your migration tracking system
    psql "$DATABASE_URL" -tAc "SELECT 1 FROM schema_migrations WHERE version = '$migration_name'" 2>/dev/null || echo "0"
}

# Run each migration
for migration in "${MIGRATIONS[@]}"; do
    migration_path="$MIGRATIONS_DIR/$migration"
    
    if [ ! -f "$migration_path" ]; then
        echo "⚠️  Migration file not found: $migration"
        continue
    fi
    
    echo "Running: $migration"
    
    # Run migration
    if psql "$DATABASE_URL" -f "$migration_path"; then
        echo "✅ $migration completed successfully"
        echo ""
    else
        echo "❌ $migration failed"
        exit 1
    fi
done

echo "=== All migrations completed successfully ==="

# Verify migrations
echo ""
echo "=== Verifying migrations ==="

# Check idempotency constraint
echo "Checking idempotency constraint..."
psql "$DATABASE_URL" -tAc "
    SELECT CASE 
        WHEN EXISTS (
            SELECT 1 FROM information_schema.table_constraints 
            WHERE constraint_name = 'ledger_entries_unique_ledger_reference'
        ) THEN '✅ Idempotency constraint exists'
        ELSE '❌ Idempotency constraint missing'
    END;
"

# Check outbox table
echo "Checking outbox table..."
psql "$DATABASE_URL" -tAc "
    SELECT CASE 
        WHEN EXISTS (
            SELECT 1 FROM information_schema.tables 
            WHERE table_name = 'dual_ledger_outbox'
        ) THEN '✅ Outbox table exists'
        ELSE '❌ Outbox table missing'
    END;
"

# Check posting function
echo "Checking posting function..."
psql "$DATABASE_URL" -tAc "
    SELECT CASE 
        WHEN EXISTS (
            SELECT 1 FROM pg_proc 
            WHERE proname = 'post_ledger_entry'
        ) THEN '✅ Posting function exists'
        ELSE '❌ Posting function missing'
    END;
"

echo ""
echo "=== Migration verification complete ==="
