#!/bin/bash

# QR Payment System V2 Validation Script
# This script validates the V2 implementation while ensuring V1 remains functional

echo "======================================"
echo "QR Payment System V2 Validation"
echo "======================================"

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

# Function to print colored output
print_status() {
    local status=$1
    local message=$2
    
    case $status in
        "SUCCESS")
            echo -e "${GREEN}✓ $message${NC}"
            ;;
        "ERROR")
            echo -e "${RED}✗ $message${NC}"
            ;;
        "WARNING")
            echo -e "${YELLOW}⚠ $message${NC}"
            ;;
        "INFO")
            echo -e "${BLUE}ℹ $message${NC}"
            ;;
    esac
}

# Function to validate file exists
check_file() {
    local file_path=$1
    local description=$2
    
    if [ -f "$file_path" ]; then
        print_status "SUCCESS" "$description exists: $file_path"
        return 0
    else
        print_status "ERROR" "$description missing: $file_path"
        return 1
    fi
}

# Function to validate directory exists
check_directory() {
    local dir_path=$1
    local description=$2
    
    if [ -d "$dir_path" ]; then
        print_status "SUCCESS" "$description exists: $dir_path"
        return 0
    else
        print_status "ERROR" "$description missing: $dir_path"
        return 1
    fi
}

# Start validation
echo -e "\n${BLUE}Phase 1: File Structure Validation${NC}"
echo "-----------------------------------"

# Check V2 core files
check_file "lib/da_product_app/qr_providers_v2/behaviour.ex" "V2 Behavior Contract"
check_file "lib/da_product_app/qr_providers_v2/types.ex" "V2 Type Definitions"
check_file "lib/da_product_app/qr_providers_v2/factory.ex" "V2 Provider Factory"
check_file "lib/da_product_app/qr_providers_v2/error_handler.ex" "V2 Error Handler"
check_file "lib/da_product_app/qr_providers_v2/response_normalizer.ex" "V2 Response Normalizer"

# Check V2 providers
check_directory "lib/da_product_app/qr_providers_v2/providers" "V2 Providers Directory"
check_file "lib/da_product_app/qr_providers_v2/providers/alipay_v2.ex" "Alipay V2 Provider"
check_file "lib/da_product_app/qr_providers_v2/providers/aani_v2.ex" "Aani V2 Provider"  
check_file "lib/da_product_app/qr_providers_v2/providers/upi_v2.ex" "UPI V2 Provider"

# Check V2 controller and routes
check_file "lib/da_product_app_web/controllers/qr_payment_controller_v2.ex" "V2 Controller"

# Check documentation
check_file "REFACTORING_PLAN_V2.md" "Refactoring Documentation"

echo -e "\n${BLUE}Phase 2: Code Structure Analysis${NC}"
echo "-----------------------------------"

# Check if V1 files still exist (ensuring no disruption)
if check_file "lib/da_product_app_web/controllers/qr_middle_layer_controller.ex" "V1 Controller (preserved)"; then
    print_status "SUCCESS" "V1 system preserved - no disruption"
fi

if check_directory "lib/da_product_app/qr_provider" "V1 Providers Directory (preserved)"; then
    print_status "SUCCESS" "V1 providers preserved"
fi

echo -e "\n${BLUE}Phase 3: Configuration Validation${NC}"
echo "-----------------------------------"

# Check if config has V2 settings
if grep -q ":qr_providers_v2" config/config.exs; then
    print_status "SUCCESS" "V2 configuration found in config.exs"
else
    print_status "WARNING" "V2 configuration not found in config.exs"
fi

# Check router has V2 routes
if grep -q "/api/v2/qr" lib/da_product_app_web/router.ex; then
    print_status "SUCCESS" "V2 routes found in router.ex"
else
    print_status "ERROR" "V2 routes missing in router.ex"
fi

echo -e "\n${BLUE}Phase 4: Compilation Check${NC}"
echo "-----------------------------------"

print_status "INFO" "Checking Elixir compilation..."

# Try to compile the project
if mix compile --warnings-as-errors 2>/dev/null; then
    print_status "SUCCESS" "Project compiles successfully with V2 system"
else
    print_status "WARNING" "Compilation issues detected - check mix compile output"
    echo "Running mix compile for detailed output:"
    mix compile
fi

echo -e "\n${BLUE}Phase 5: Dependency Analysis${NC}"  
echo "-----------------------------------"

# Check if all required modules can be loaded
print_status "INFO" "Validating module dependencies..."

# Test if V2 modules are loadable
elixir -e "
try do
  Code.ensure_loaded(DaProductApp.QRProvidersV2)
  Code.ensure_loaded(DaProductApp.QRProvidersV2.Types) 
  Code.ensure_loaded(DaProductApp.QRProvidersV2.Behaviour)
  Code.ensure_loaded(DaProductApp.QRProvidersV2.Factory)
  IO.puts('SUCCESS: All V2 core modules loadable')
rescue
  e -> IO.puts('ERROR: Module loading failed - #{inspect(e)}')
end
" 2>/dev/null && print_status "SUCCESS" "V2 core modules loadable" || print_status "ERROR" "V2 module loading issues"

echo -e "\n${BLUE}Phase 6: Database Schema Compatibility${NC}"
echo "-----------------------------------"

# Check if migrations are up to date
if mix ecto.migrations 2>/dev/null | grep -q "up"; then
    print_status "SUCCESS" "Database migrations up to date"
else
    print_status "WARNING" "Database migrations may need attention"
fi

echo -e "\n${BLUE}Phase 7: Test Coverage Validation${NC}"
echo "-----------------------------------"

# Check if test files exist
check_file "test/da_product_app_web/controllers/qr_payment_controller_v2_test.exs" "V2 Controller Tests"

# Try to run tests (if available)
if [ -f "test/da_product_app_web/controllers/qr_payment_controller_v2_test.exs" ]; then
    print_status "INFO" "Running V2 controller tests..."
    if mix test test/da_product_app_web/controllers/qr_payment_controller_v2_test.exs --no-start 2>/dev/null; then
        print_status "SUCCESS" "V2 tests pass"
    else
        print_status "WARNING" "V2 tests need database setup - run 'mix test' with proper setup"
    fi
fi

echo -e "\n${BLUE}Phase 8: API Endpoint Validation${NC}"
echo "-----------------------------------"

print_status "INFO" "Checking V2 API endpoints in router..."

# Check each V2 endpoint exists in router
v2_endpoints=("generate" "cancel" "refund" "inquiry" "providers" "health")

for endpoint in "${v2_endpoints[@]}"; do
    if grep -q "/$endpoint.*QRPaymentControllerV2" lib/da_product_app_web/router.ex; then
        print_status "SUCCESS" "V2 endpoint /$endpoint configured"
    else
        print_status "ERROR" "V2 endpoint /$endpoint missing"
    fi
done

echo -e "\n${BLUE}Phase 9: Backward Compatibility Check${NC}"
echo "-----------------------------------"

# Ensure V1 endpoints still exist
v1_endpoints=("processTransaction" "cancelPayment" "refundPayment")

for endpoint in "${v1_endpoints[@]}"; do
    if grep -q "/$endpoint.*QRMiddleLayerController" lib/da_product_app_web/router.ex; then
        print_status "SUCCESS" "V1 endpoint /$endpoint preserved"
    else
        print_status "ERROR" "V1 endpoint /$endpoint missing - backward compatibility broken!"
    fi
done

echo -e "\n${BLUE}Validation Summary${NC}"
echo "-----------------------------------"

print_status "INFO" "V2 QR Payment System validation completed"
print_status "INFO" "Key Benefits of V2 Implementation:"
echo "   • Standardized provider interfaces"
echo "   • Enhanced error handling and logging" 
echo "   • Provider-agnostic controller logic"
echo "   • Zero disruption to existing V1 system"
echo "   • Easy addition of new payment providers"
echo "   • Comprehensive monitoring and metrics"

echo -e "\n${GREEN}Next Steps:${NC}"
echo "1. Run 'mix test' to execute full test suite"
echo "2. Start server with 'mix phx.server'" 
echo "3. Test V2 endpoints: POST /api/v2/qr/generate"
echo "4. Validate V1 endpoints still work: POST /api/processTransaction"
echo "5. Monitor logs for V2 system performance"

echo -e "\n${BLUE}V2 API Endpoints Available:${NC}"
echo "• POST /api/v2/qr/generate - Generate QR code"
echo "• POST /api/v2/qr/cancel - Cancel payment"
echo "• POST /api/v2/qr/refund - Process refund"
echo "• POST /api/v2/qr/inquiry - Check payment status"
echo "• GET  /api/v2/qr/providers - List providers"
echo "• GET  /api/v2/qr/health - System health check"

echo -e "\n======================================"