#!/bin/bash

# Script: Migrate Blocked Seats to Active Status
# Purpose: Update existing blocked seats from is_active=false to is_active=true
# Date: 2025-11-11
# Related: STORY-ADMIN-001, QA_BLOCKED_SEATS_IS_ACTIVE_CHANGE.md

set -e  # Exit on error

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

echo "════════════════════════════════════════════════════════════════"
echo "  Migrate Blocked Seats to Active Status"
echo "════════════════════════════════════════════════════════════════"
echo ""
echo "This script updates existing blocked seats to is_active=true"
echo "so they appear in the availability API with customer notes."
echo ""

# Check if we're in the right directory
if [ ! -f "$PROJECT_ROOT/artisan" ]; then
    echo "❌ Error: Cannot find artisan file"
    echo "   This script must be run from the project root or scripts directory"
    exit 1
fi

cd "$PROJECT_ROOT"

# Safety check: Show what will be updated
echo "Step 1: Analyzing current blocked seats..."
echo ""

php artisan tinker --execute="
\$blockedSeats = DB::table('seats as s')
    ->join('seat_reservations as sr', function(\$join) {
        \$join->on('s.seat_id', '=', 'sr.seat_id')
             ->on('s.event_id', '=', 'sr.event_id');
    })
    ->where('sr.status', 'blocked')
    ->where('s.is_active', false)
    ->select('s.id', 's.seat_number', 's.event_id', 'sr.notes')
    ->get();

echo '📊 Found ' . \$blockedSeats->count() . ' blocked seats with is_active=false' . PHP_EOL;
echo PHP_EOL;

if (\$blockedSeats->isEmpty()) {
    echo '✅ No migration needed - all blocked seats already active!' . PHP_EOL;
    exit(0);
}

// Show sample seats
echo 'Sample blocked seats to be updated:' . PHP_EOL;
foreach (\$blockedSeats->take(10) as \$seat) {
    echo '  - Event ' . \$seat->event_id . ': ' . \$seat->seat_number;
    if (\$seat->notes) {
        echo ' (note: \"' . \$seat->notes . '\")';
    }
    echo PHP_EOL;
}

if (\$blockedSeats->count() > 10) {
    echo '  ... and ' . (\$blockedSeats->count() - 10) . ' more' . PHP_EOL;
}
"

# Check if we found any seats to migrate
SEAT_COUNT=$(php artisan tinker --execute="
\$count = DB::table('seats as s')
    ->join('seat_reservations as sr', function(\$join) {
        \$join->on('s.seat_id', '=', 'sr.seat_id')
             ->on('s.event_id', '=', 'sr.event_id');
    })
    ->where('sr.status', 'blocked')
    ->where('s.is_active', false)
    ->count();
echo \$count;
" 2>/dev/null | tail -1)

if [ "$SEAT_COUNT" = "0" ]; then
    echo ""
    echo "✅ Migration complete - no seats to update!"
    exit 0
fi

echo ""
echo "⚠️  This will update $SEAT_COUNT seat(s) from is_active=false to is_active=true"
echo ""
read -p "Continue with migration? (yes/no): " CONFIRM

if [ "$CONFIRM" != "yes" ]; then
    echo "❌ Migration cancelled by user"
    exit 1
fi

echo ""
echo "Step 2: Running migration..."
echo ""

# Run the migration
php artisan tinker --execute="
\$updated = DB::table('seats as s')
    ->join('seat_reservations as sr', function(\$join) {
        \$join->on('s.seat_id', '=', 'sr.seat_id')
             ->on('s.event_id', '=', 'sr.event_id');
    })
    ->where('sr.status', 'blocked')
    ->where('s.is_active', false)
    ->update([
        's.is_active' => true,
        's.updated_at' => now()
    ]);

echo '✅ Updated ' . \$updated . ' seat(s) to is_active=true' . PHP_EOL;
"

echo ""
echo "Step 3: Verification..."
echo ""

# Verify no blocked seats remain with is_active=false
php artisan tinker --execute="
\$remaining = DB::table('seats as s')
    ->join('seat_reservations as sr', function(\$join) {
        \$join->on('s.seat_id', '=', 'sr.seat_id')
             ->on('s.event_id', '=', 'sr.event_id');
    })
    ->where('sr.status', 'blocked')
    ->where('s.is_active', false)
    ->count();

if (\$remaining > 0) {
    echo '⚠️  Warning: ' . \$remaining . ' blocked seats still have is_active=false' . PHP_EOL;
    exit(1);
} else {
    echo '✅ Verification passed: All blocked seats now have is_active=true' . PHP_EOL;
}

// Show final statistics
\$totalBlocked = DB::table('seat_reservations')
    ->where('status', 'blocked')
    ->count();

echo PHP_EOL;
echo '📊 Final Statistics:' . PHP_EOL;
echo '   Total blocked reservations: ' . \$totalBlocked . PHP_EOL;
echo '   All seats active: ✅' . PHP_EOL;
"

echo ""
echo "════════════════════════════════════════════════════════════════"
echo "  Migration Complete!"
echo "════════════════════════════════════════════════════════════════"
echo ""
echo "Next steps:"
echo "  1. Test availability API - blocked seats should now appear"
echo "  2. Test booking API - blocked seats should return 409 Conflict"
echo "  3. Test statistics - total_seats count should increase"
echo ""
