#!/bin/bash

# Script to generate a comprehensive test report for the subscription creation flow
# This script checks all components and generates a detailed report

echo "📊 Generating Subscription Creation Flow Test Report"
echo "===================================================="
echo "Report generated on: $(date)"
echo ""

# Test 1: Check if database migration was applied
echo "🔍 Test 1: Database Migration Check"
echo "-----------------------------------"
POD_NAME=$(kubectl get pods -n bakery-ia -l app=auth-service -o jsonpath='{.items[0].metadata.name}')
MIGRATION_STATUS=$(kubectl exec -n bakery-ia $POD_NAME -- psql -U auth_user -d auth_db -c "SELECT version_num FROM alembic_version" -t -A)

if [[ "$MIGRATION_STATUS" == "20260113_add_payment_columns" ]]; then
    echo "✅ PASS: Database migration '20260113_add_payment_columns' is applied"
else
    echo "❌ FAIL: Database migration not found. Current version: $MIGRATION_STATUS"
fi
echo ""

# Test 2: Check if payment columns exist in users table
echo "🔍 Test 2: Payment Columns in Users Table"
echo "------------------------------------------"
COLUMNS=$(kubectl exec -n bakery-ia $POD_NAME -- psql -U auth_user -d auth_db -c "\d users" -t -A | grep -E "payment_customer_id|default_payment_method_id")

if [[ -n "$COLUMNS" ]]; then
    echo "✅ PASS: Payment columns found in users table"
    echo "   Found columns:"
    echo "   $COLUMNS" | sed 's/^/   /'
else
    echo "❌ FAIL: Payment columns not found in users table"
fi
echo ""

# Test 3: Check if gateway route exists
echo "🔍 Test 3: Gateway Route Configuration"
echo "--------------------------------------"
GATEWAY_POD=$(kubectl get pods -n bakery-ia -l app=gateway -o jsonpath='{.items[0].metadata.name}')
ROUTE_CHECK=$(kubectl exec -n bakery-ia $GATEWAY_POD -- grep -c "create-for-registration" /app/app/routes/subscription.py)

if [[ "$ROUTE_CHECK" -gt 0 ]]; then
    echo "✅ PASS: Gateway route for 'create-for-registration' is configured"
else
    echo "❌ FAIL: Gateway route for 'create-for-registration' not found"
fi
echo ""

# Test 4: Check if tenant service endpoint exists
echo "🔍 Test 4: Tenant Service Endpoint"
echo "-----------------------------------"
TENANT_POD=$(kubectl get pods -n bakery-ia -l app=tenant-service -o jsonpath='{.items[0].metadata.name}')
ENDPOINT_CHECK=$(kubectl exec -n bakery-ia $TENANT_POD -- grep -c "create-for-registration" /app/app/api/subscription.py)

if [[ "$ENDPOINT_CHECK" -gt 0 ]]; then
    echo "✅ PASS: Tenant service endpoint 'create-for-registration' is configured"
else
    echo "❌ FAIL: Tenant service endpoint 'create-for-registration' not found"
fi
echo ""

# Test 5: Test user registration (create a test user)
echo "🔍 Test 5: User Registration Test"
echo "--------------------------------"
TEST_EMAIL="test_$(date +%Y%m%d%H%M%S)@example.com"
REGISTRATION_RESPONSE=$(curl -X POST "https://bakery-ia.local/api/v1/auth/register-with-subscription" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -d "{\"email\":\"$TEST_EMAIL\",\"password\":\"SecurePassword123!\",\"full_name\":\"Test User\",\"subscription_plan\":\"basic\",\"payment_method_id\":\"pm_test123\"}" \
    -k -s)

if echo "$REGISTRATION_RESPONSE" | grep -q "access_token"; then
    echo "✅ PASS: User registration successful"
    USER_ID=$(echo "$REGISTRATION_RESPONSE" | python3 -c "import sys, json; print(json.load(sys.stdin)['user']['id'])")
    echo "   Created user ID: $USER_ID"
else
    echo "❌ FAIL: User registration failed"
    echo "   Response: $REGISTRATION_RESPONSE"
fi
echo ""

# Test 6: Check if user has payment fields
echo "🔍 Test 6: User Payment Fields"
echo "------------------------------"
if [[ -n "$USER_ID" ]]; then
    USER_DATA=$(kubectl exec -n bakery-ia $POD_NAME -- psql -U auth_user -d auth_db -c "SELECT payment_customer_id, default_payment_method_id FROM users WHERE id = '$USER_ID'" -t -A)
    
    if [[ -n "$USER_DATA" ]]; then
        echo "✅ PASS: User has payment fields in database"
        echo "   Payment data: $USER_DATA"
    else
        echo "❌ FAIL: User payment fields not found"
    fi
else
    echo "⚠️  SKIP: User ID not available from previous test"
fi
echo ""

# Test 7: Check subscription creation in onboarding progress
echo "🔍 Test 7: Subscription in Onboarding Progress"
echo "---------------------------------------------"
if [[ -n "$USER_ID" ]]; then
    # This would require authentication, so we'll skip for now
    echo "⚠️  SKIP: Requires authentication (would need to implement token handling)"
else
    echo "⚠️  SKIP: User ID not available from previous test"
fi
echo ""

# Summary
echo "📋 Test Summary"
echo "==============="
echo "The subscription creation flow test report has been generated."
echo ""
echo "Components tested:"
echo "  1. Database migration"
echo "  2. Payment columns in users table"
echo "  3. Gateway route configuration"
echo "  4. Tenant service endpoint"
echo "  5. User registration"
echo "  6. User payment fields"
echo "  7. Subscription in onboarding progress"
echo ""
echo "For a complete integration test, run:"
echo "  ./scripts/run_subscription_integration_test.sh"
echo ""
echo "🎉 Report generation completed!"