#!/bin/bash
########################################
# Cleanup Test Files from Production
# Removes test scripts and test data
########################################

set -e

echo "═══════════════════════════════════════════════════════════"
echo "  PRODUCTION TEST FILE CLEANUP"
echo "═══════════════════════════════════════════════════════════"
echo ""

# Check if we're on production
if [ ! -f ".env" ]; then
    echo "❌ Error: .env not found. Run this from the Laravel root directory."
    exit 1
fi

# Step 1: Backup test files
echo "Step 1: Backing up test files..."
echo "─────────────────────────────────────────────────────────"

mkdir -p ~/test-scripts-backup
if ls test*.php 1> /dev/null 2>&1; then
    cp test*.php ~/test-scripts-backup/ 2>/dev/null || true
    echo "✅ Test files backed up to ~/test-scripts-backup/"
else
    echo "ℹ️  No test files found to backup"
fi
echo ""

# Step 2: Remove test files
echo "Step 2: Removing test files from production..."
echo "─────────────────────────────────────────────────────────"

REMOVED=0
for file in test*.php; do
    if [ -f "$file" ]; then
        echo "  Removing: $file"
        rm "$file"
        ((REMOVED++))
    fi
done

if [ $REMOVED -eq 0 ]; then
    echo "ℹ️  No test files found"
else
    echo "✅ Removed $REMOVED test file(s)"
fi
echo ""

# Step 3: Clean up test data in database
echo "Step 3: Cleaning up test data from database..."
echo "─────────────────────────────────────────────────────────"

# Source database helper
if [ -f "scripts/_db-helper.sh" ]; then
    source scripts/_db-helper.sh

    # Count test orders
    TEST_ORDER_COUNT=$(db_query "SELECT COUNT(*) FROM orders WHERE customer_email LIKE '%@example.com'" | tail -1)

    if [ "$TEST_ORDER_COUNT" -gt 0 ]; then
        echo "Found $TEST_ORDER_COUNT test order(s) with @example.com emails"
        echo ""
        echo "⚠️  About to delete:"
        echo "  - Test orders (customer_email LIKE '%@example.com')"
        echo "  - Their associated seat_reservations"
        echo ""
        read -p "Continue? (y/N): " -n 1 -r
        echo ""

        if [[ $REPLY =~ ^[Yy]$ ]]; then
            # Delete test seat_reservations first
            db_query "DELETE sr FROM seat_reservations sr
                     INNER JOIN orders o ON sr.order_id = o.id
                     WHERE o.customer_email LIKE '%@example.com'"

            # Delete test orders
            db_query "DELETE FROM orders WHERE customer_email LIKE '%@example.com'"

            echo "✅ Test data deleted successfully"
        else
            echo "ℹ️  Skipped database cleanup"
        fi
    else
        echo "✅ No test orders found in database"
    fi
else
    echo "⚠️  Database helper not found - skipping database cleanup"
    echo "   Run manually: DELETE FROM orders WHERE customer_email LIKE '%@example.com'"
fi
echo ""

# Step 4: Verify cleanup
echo "Step 4: Verification"
echo "─────────────────────────────────────────────────────────"

if ls test*.php 1> /dev/null 2>&1; then
    echo "⚠️  Test files still present:"
    ls -la test*.php
else
    echo "✅ No test files in production directory"
fi

echo ""
echo "═══════════════════════════════════════════════════════════"
echo "  CLEANUP COMPLETE!"
echo "═══════════════════════════════════════════════════════════"
echo ""
echo "✅ Test files removed from production"
echo "✅ Test data cleaned from database"
echo "✅ Backup saved to ~/test-scripts-backup/"
echo ""
echo "Next steps:"
echo "  1. Verify test URLs return 404:"
echo "     curl -I https://api.globalgala.com/test-complete-vip-flow.php"
echo "  2. Monitor for new test orders in next 24 hours"
echo ""
