#!/bin/bash
# Test Payment System Fixes on Dev Server
# Run this on dev server after deployment

set -e

echo "======================================"
echo "Payment System Fixes - Dev Server Test"
echo "======================================"
echo ""

# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Load database helper
source scripts/_db-helper.sh

echo "📊 Step 1: Check current database state"
echo "========================================"
echo ""

echo "Total orders:"
db_count orders

echo ""
echo "Orders by payment method:"
db_table "SELECT
    COALESCE(payment_method, 'NULL') as payment_method,
    COUNT(*) as count,
    MIN(created_at) as earliest,
    MAX(created_at) as latest
FROM orders
GROUP BY payment_method
ORDER BY count DESC"

echo ""
echo "Orders needing backfill (NULL payment_method with Revolut IDs):"
NEED_BACKFILL=$(db_query "SELECT COUNT(*) FROM orders
    WHERE (payment_method IS NULL OR payment_method = '')
    AND revolut_order_id IS NOT NULL")
echo "$NEED_BACKFILL orders"

echo ""
echo "📋 Step 2: Test PaymentDisplayService"
echo "======================================"
echo ""

php artisan tinker --execute="
\$order = \App\Model\Order::whereNotNull('revolut_order_id')->first();
if (\$order) {
    echo 'Testing with Order #' . \$order->id . '\n';
    \$display = \App\Services\PaymentDisplayService::getPaymentDisplay(\$order);
    echo 'Method: ' . \$display['method'] . '\n';
    echo 'Status: ' . \$display['status'] . '\n';
    echo 'ID Masked: ' . \$display['id_masked'] . '\n';
} else {
    echo 'No Revolut orders found\n';
}
"

echo ""
echo "💾 Step 3: Test backfill script (DRY RUN)"
echo "=========================================="
echo ""

php scripts/backfill-payment-method.php --dry-run | head -20

echo ""
echo "📧 Step 4: Check payment_transactions table"
echo "============================================"
echo ""

echo "Current payment_transactions count:"
db_count payment_transactions

echo ""
echo "Recent payment transactions (if any):"
db_table "SELECT id, order_id, payment_gateway, status, created_at
FROM payment_transactions
ORDER BY created_at DESC
LIMIT 5"

echo ""
echo "🧪 Step 5: Sample orders for manual email testing"
echo "=================================================="
echo ""

db_table "SELECT
    id,
    customer_email,
    payment_method,
    revolut_order_id IS NOT NULL as has_revolut,
    created_at
FROM orders
WHERE customer_email IS NOT NULL
ORDER BY created_at DESC
LIMIT 3"

echo ""
echo "📝 Next Steps:"
echo "=============="
echo ""
echo "1. Review the data above"
echo "2. If backfill needed, run: php scripts/backfill-payment-method.php"
echo "3. Verify payment_method is set after backfill"
echo "4. Test email: php artisan tickets:regenerate-and-resend --order-id=<ID>"
echo "5. Create test order via webhook to verify new transactions are recorded"
echo ""
echo "✅ Test script complete!"
