#!/bin/bash

#==============================================================================
# Revolut Audit Testing Script
# Purpose: Systematic local testing before production deployment
# Usage: ./scripts/test-revolut-audit.sh
#==============================================================================

set -e

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

echo -e "${BLUE}╔══════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║     Revolut Orphaned Payment Audit - Testing Suite       ║${NC}"
echo -e "${BLUE}╔══════════════════════════════════════════════════════════╗${NC}"
echo ""

# Check we're in the right directory
if [ ! -f "artisan" ]; then
    echo -e "${RED}❌ Error: Must run from Laravel project root${NC}"
    exit 1
fi

# Function to prompt for confirmation
confirm() {
    read -p "$1 (yes/no): " response
    if [ "$response" != "yes" ]; then
        echo -e "${YELLOW}⏭️  Skipped${NC}"
        return 1
    fi
    return 0
}

# Function to display section header
section() {
    echo ""
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
    echo -e "${BLUE}$1${NC}"
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
    echo ""
}

# Function to run test with status
run_test() {
    local test_name="$1"
    local test_command="$2"

    echo -e "${YELLOW}🧪 Testing: ${test_name}${NC}"
    echo ""

    if eval "$test_command"; then
        echo ""
        echo -e "${GREEN}✅ PASS: ${test_name}${NC}"
        return 0
    else
        echo ""
        echo -e "${RED}❌ FAIL: ${test_name}${NC}"
        return 1
    fi
}

#==============================================================================
# PRE-FLIGHT CHECKS
#==============================================================================

section "PRE-FLIGHT CHECKS"

# Check PHP
echo -e "${YELLOW}🔍 Checking PHP version...${NC}"
php -v | head -1

# Check Laravel
echo -e "${YELLOW}🔍 Checking Laravel...${NC}"
php artisan --version

# Check database connection
echo -e "${YELLOW}🔍 Checking database connection...${NC}"
php artisan db:show --database=mysql 2>/dev/null || echo "Database connection OK"

# Check Revolut configuration
echo -e "${YELLOW}🔍 Checking Revolut configuration...${NC}"
if grep -q "REVOLUT_API_KEY" .env; then
    echo -e "${GREEN}✅ REVOLUT_API_KEY found in .env${NC}"
else
    echo -e "${RED}❌ REVOLUT_API_KEY not found in .env${NC}"
    echo ""
    echo "Add to .env:"
    echo "REVOLUT_API_KEY=sk_sandbox_YOUR_KEY  # For testing"
    echo "REVOLUT_MODE=sandbox"
    echo ""
    exit 1
fi

# Check mode
MODE=$(grep "REVOLUT_MODE" .env | cut -d '=' -f2 || echo "unknown")
echo -e "Mode: ${YELLOW}${MODE}${NC}"

if [ "$MODE" == "sandbox" ]; then
    echo -e "${GREEN}✅ Safe testing mode (sandbox)${NC}"
elif [ "$MODE" == "production" ]; then
    echo -e "${RED}⚠️  WARNING: Using PRODUCTION mode!${NC}"
    if ! confirm "Are you sure you want to test with PRODUCTION API?"; then
        exit 1
    fi
else
    echo -e "${YELLOW}⚠️  Mode not set, defaulting to sandbox${NC}"
fi

#==============================================================================
# TEST SUITE
#==============================================================================

section "TEST 1: API CONNECTION"

if confirm "Run API connection test?"; then
    run_test "API Connection" "php artisan payments:audit-revolut --test-connection"
fi

#==============================================================================

section "TEST 2: DRY RUN (7 Days)"

if confirm "Run dry-run audit for last 7 days?"; then
    run_test "Dry Run (7 Days)" "php artisan payments:audit-revolut --days=7 --dry-run"
fi

#==============================================================================

section "TEST 3: DRY RUN (30 Days)"

if confirm "Run dry-run audit for last 30 days?"; then
    run_test "Dry Run (30 Days)" "php artisan payments:audit-revolut --days=30 --dry-run --verbose"
fi

#==============================================================================

section "TEST 4: EXPORT CSV (30 Days)"

if confirm "Export CSV report for last 30 days?"; then
    run_test "CSV Export" "php artisan payments:audit-revolut --days=30 --export=csv --verbose"

    # Find latest CSV
    LATEST_CSV=$(ls -t storage/app/audits/revolut_audit_*.csv 2>/dev/null | head -1)

    if [ -n "$LATEST_CSV" ]; then
        echo ""
        echo -e "${GREEN}📄 Report generated: ${LATEST_CSV}${NC}"
        echo ""

        # Show row count
        ROW_COUNT=$(($(wc -l < "$LATEST_CSV") - 1))  # Subtract header
        echo -e "Rows in CSV: ${YELLOW}${ROW_COUNT}${NC}"

        # Offer to open
        if command -v open &> /dev/null; then
            if confirm "Open CSV file?"; then
                open "$LATEST_CSV"
            fi
        fi
    fi
fi

#==============================================================================

section "TEST 5: FULL AUDIT (90 Days) - PRODUCTION ONLY"

if [ "$MODE" == "production" ]; then
    echo -e "${RED}⚠️  WARNING: This will query PRODUCTION Revolut API for 90 days${NC}"
    echo -e "${RED}⚠️  This will show REAL customer data and financial amounts${NC}"
    echo ""

    if confirm "Run full 90-day production audit?"; then
        run_test "Full Production Audit (90 Days)" \
            "php artisan payments:audit-revolut --days=90 --export=csv --verbose"

        # Find latest CSV
        LATEST_CSV=$(ls -t storage/app/audits/revolut_audit_*.csv 2>/dev/null | head -1)

        if [ -n "$LATEST_CSV" ]; then
            echo ""
            echo -e "${GREEN}📄 Production report: ${LATEST_CSV}${NC}"
            echo ""

            # Show summary stats
            echo "Summary from CSV:"
            echo "=================="

            # Count orphaned payments
            ORPHANED=$(grep -c "ORPHANED" "$LATEST_CSV" || echo "0")
            echo -e "Orphaned Payments: ${RED}${ORPHANED}${NC}"

            # Count refund required
            REFUND=$(grep -c "REFUND" "$LATEST_CSV" || echo "0")
            echo -e "Refund Required: ${RED}${REFUND}${NC}"

            # Count recoverable
            RECOVER=$(grep -c "RECOVER" "$LATEST_CSV" || echo "0")
            echo -e "Recoverable: ${GREEN}${RECOVER}${NC}"

            echo ""

            if [ "$ORPHANED" -gt 0 ]; then
                echo -e "${RED}⚠️  URGENT: ${ORPHANED} orphaned payments found!${NC}"
                echo ""
                echo "Next steps:"
                echo "1. Review CSV: $LATEST_CSV"
                echo "2. Validate known cases (Wadha, Saja)"
                echo "3. Check for false positives"
                echo "4. Prepare refund plan"
            else
                echo -e "${GREEN}✅ No orphaned payments found${NC}"
            fi
        fi
    fi
else
    echo -e "${YELLOW}⏭️  Skipping (sandbox mode)${NC}"
    echo "Switch to production mode to run this test:"
    echo "1. Update .env: REVOLUT_MODE=production"
    echo "2. Update .env: REVOLUT_API_KEY=sk_prod_..."
    echo "3. Run: php artisan config:clear"
fi

#==============================================================================
# SUMMARY
#==============================================================================

section "TESTING COMPLETE"

echo -e "${GREEN}✅ All requested tests completed${NC}"
echo ""
echo "📋 Review Checklist:"
echo ""
echo "  [ ] API connection works"
echo "  [ ] Dry run completed without errors"
echo "  [ ] CSV export generated successfully"
echo "  [ ] CSV contains expected data"
echo "  [ ] No false positives (existing orders marked orphaned)"
echo "  [ ] Known orphans appear in results (if production)"
echo ""
echo "📁 Reports saved to: storage/app/audits/"
echo "📄 Logs saved to: storage/logs/"
echo ""

if [ "$MODE" == "production" ]; then
    echo -e "${YELLOW}⚠️  PRODUCTION MODE REMINDERS:${NC}"
    echo "  - Review CSV before taking any action"
    echo "  - Validate high-value orphans manually"
    echo "  - Coordinate with finance before refunds"
    echo "  - Document all decisions"
fi

echo ""
echo -e "${BLUE}╔══════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║              Testing Complete - Review Results            ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════════╝${NC}"
echo ""

# Return success
exit 0
