#!/bin/bash

# Supabase integration validation for Trip With Us

echo "=== Supabase Integration Validation ==="

# Configuration
SUPABASE_PORT=54321
TIMEOUT=30

# Check Supabase CLI
echo "🔍 Checking Supabase CLI..."
if command -v supabase >/dev/null 2>&1; then
    supabase_version=$(supabase --version 2>&1 | head -1)
    echo "✅ Supabase CLI: $supabase_version"
else
    echo "❌ Supabase CLI not found"
    exit 1
fi

# Check if Supabase is running
echo "🔍 Checking Supabase status..."
if pgrep -f "supabase" > /dev/null; then
    echo "✅ Supabase process running"
    
    # Check API accessibility
    if curl -s "http://localhost:$SUPABASE_PORT/health" >/dev/null 2>&1; then
        echo "✅ Supabase API accessible on port $SUPABASE_PORT"
    else
        echo "❌ Supabase API not responding on port $SUPABASE_PORT"
        exit 1
    fi
else
    echo "❌ Supabase not running"
    echo "Start with: supabase start"
    exit 1
fi

# Validate environment configuration
echo "🔍 Checking environment configuration..."

# Check for required environment variables
required_env_vars=("VITE_SUPABASE_URL" "VITE_SUPABASE_ANON_KEY")
env_issues=0

# Source .env file if it exists
if [ -f "../../.env" ]; then
    export $(cat ../../.env | grep -v '^#' | xargs)
fi

for var in "${required_env_vars[@]}"; do
    if [ -z "${!var}" ]; then
        echo "❌ Missing environment variable: $var"
        ((env_issues++))
    else
        echo "✅ $var: Configured"
    fi
done

if [ "$env_issues" -gt 0 ]; then
    echo "⚠️  $env_issues environment configuration issues"
else
    echo "✅ All required environment variables configured"
fi

# Check Supabase configuration file
echo "🔍 Checking Supabase configuration..."
if [ -f "../../supabase/config.toml" ]; then
    echo "✅ Supabase config file found"
    
    # Check key configuration values
    if grep -q "port = $SUPABASE_PORT" ../../supabase/config.toml; then
        echo "✅ API port correctly configured"
    else
        echo "⚠️  API port configuration may be incorrect"
    fi
    
    # Check database configuration
    if grep -q "enabled = true" ../../supabase/config.toml | head -1 >/dev/null; then
        echo "✅ Database enabled in config"
    else
        echo "⚠️  Database configuration unclear"
    fi
else
    echo "❌ Supabase config file not found"
    echo "Initialize with: supabase init"
    exit 1
fi

# Validate database schema
echo "🔍 Validating database schema..."
if [ -d "../../supabase/migrations" ]; then
    migration_count=$(find ../../supabase/migrations -name "*.sql" | wc -l)
    echo "✅ Found $migration_count migration files"
    
    if [ "$migration_count" -gt 0 ]; then
        # Check for recent migrations
        recent_migrations=$(find ../../supabase/migrations -name "*.sql" -mtime -7 | wc -l)
        if [ "$recent_migrations" -gt 0 ]; then
            echo "✅ $recent_migrations recent migrations (last 7 days)"
        else
            echo "ℹ️  No recent migrations"
        fi
        
        # Validate migration naming
        invalid_names=$(find ../../supabase/migrations -name "*.sql" ! -name "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]_*.sql" | wc -l)
        if [ "$invalid_names" -eq 0 ]; then
            echo "✅ All migrations follow naming convention"
        else
            echo "⚠️  $invalid_names migrations with non-standard names"
        fi
    fi
else
    echo "⚠️  No migrations directory found"
fi

# Check TypeScript type generation
echo "🔍 Checking TypeScript type generation..."
if [ -f "../../src/types/supabase.ts" ]; then
    echo "✅ Supabase types file exists"
    
    # Check if types are recent
    types_age=$(find ../../src/types/supabase.ts -mtime +1 2>/dev/null | wc -l)
    if [ "$types_age" -eq 0 ]; then
        echo "✅ Types file is recent (< 1 day old)"
    else
        echo "⚠️  Types file is old (> 1 day)"
        echo "Update with: supabase gen types typescript --local > src/types/supabase.ts"
    fi
    
    # Check type file size (should not be tiny)
    type_size=$(wc -l < ../../src/types/supabase.ts 2>/dev/null || echo "0")
    if [ "$type_size" -gt 50 ]; then
        echo "✅ Types file appears complete ($type_size lines)"
    else
        echo "⚠️  Types file seems incomplete ($type_size lines)"
    fi
else
    echo "❌ Supabase types file not found"
    echo "Generate with: supabase gen types typescript --local > src/types/supabase.ts"
fi

# Test database connection
echo "🔍 Testing database connection..."
connection_test=$(curl -s -X POST "http://localhost:$SUPABASE_PORT/rest/v1/rpc/pg_version" \
    -H "apikey: ${VITE_SUPABASE_ANON_KEY:-}" \
    -H "Authorization: Bearer ${VITE_SUPABASE_ANON_KEY:-}" \
    2>/dev/null)

if [ -n "$connection_test" ]; then
    echo "✅ Database connection successful"
    
    # Extract PostgreSQL version if available
    if echo "$connection_test" | grep -q "PostgreSQL"; then
        pg_version=$(echo "$connection_test" | grep -o "PostgreSQL [0-9.]*" || echo "PostgreSQL (version unknown)")
        echo "✅ Database: $pg_version"
    fi
else
    echo "❌ Database connection failed"
    echo "Check your VITE_SUPABASE_ANON_KEY and API accessibility"
fi

# Check Row Level Security (RLS) policies
echo "🔍 Checking RLS policies..."
if [ -d "../../supabase/migrations" ]; then
    rls_policies=$(grep -r "CREATE POLICY\|ENABLE ROW LEVEL SECURITY" ../../supabase/migrations --include="*.sql" | wc -l)
    if [ "$rls_policies" -gt 0 ]; then
        echo "✅ Found $rls_policies RLS policies/enablements"
        
        # Check for common Trip With Us tables
        trip_rls=$(grep -r "trips.*ENABLE ROW LEVEL SECURITY\|CREATE POLICY.*trips" ../../supabase/migrations --include="*.sql" | wc -l)
        user_rls=$(grep -r "profiles.*ENABLE ROW LEVEL SECURITY\|CREATE POLICY.*profiles" ../../supabase/migrations --include="*.sql" | wc -l)
        
        echo "  Trip RLS policies: $trip_rls"
        echo "  User RLS policies: $user_rls"
    else
        echo "⚠️  No RLS policies found"
        echo "Consider implementing RLS for data security"
    fi
fi

# Check Supabase client usage in code
echo "🔍 Analyzing Supabase client usage..."
supabase_imports=$(grep -r "from.*@supabase/supabase-js" ../../src/ --include="*.ts" --include="*.tsx" | wc -l)
supabase_clients=$(grep -r "createClient\|supabase\." ../../src/ --include="*.ts" --include="*.tsx" | wc -l)

echo "✅ Supabase imports: $supabase_imports files"
echo "✅ Supabase client usage: $supabase_clients instances"

# Check for proper error handling patterns
error_handling=$(grep -r "supabase.*error\|\.error" ../../src/ --include="*.ts" --include="*.tsx" | wc -l)
if [ "$error_handling" -gt 0 ]; then
    echo "✅ Found $error_handling error handling instances"
else
    echo "⚠️  Limited error handling found"
    echo "Consider adding more comprehensive error handling"
fi

# Check realtime subscriptions
realtime_usage=$(grep -r "subscribe\|channel\|on('postgres_changes'" ../../src/ --include="*.ts" --include="*.tsx" | wc -l)
if [ "$realtime_usage" -gt 0 ]; then
    echo "✅ Found $realtime_usage realtime subscription instances"
else
    echo "ℹ️  No realtime subscriptions found"
fi

# Storage usage check
storage_usage=$(grep -r "\.storage\.\|from('.*')" ../../src/ --include="*.ts" --include="*.tsx" | wc -l)
if [ "$storage_usage" -gt 0 ]; then
    echo "✅ Found $storage_usage storage operations"
else
    echo "ℹ️  No storage operations found"
fi

# Generate Supabase validation report
cat > ../state/supabase-validation-report.json << EOF
{
  "timestamp": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")",
  "cli_available": true,
  "service_running": true,
  "api_accessible": true,
  "environment_configured": $([ "$env_issues" -eq 0 ] && echo "true" || echo "false"),
  "config_file_exists": $([ -f "../../supabase/config.toml" ] && echo "true" || echo "false"),
  "migration_count": ${migration_count:-0},
  "types_file_exists": $([ -f "../../src/types/supabase.ts" ] && echo "true" || echo "false"),
  "types_file_recent": $([ "${types_age:-1}" -eq 0 ] && echo "true" || echo "false"),
  "database_connection": $([ -n "$connection_test" ] && echo "true" || echo "false"),
  "rls_policies": ${rls_policies:-0},
  "code_integration": {
    "import_count": $supabase_imports,
    "client_usage": $supabase_clients,
    "error_handling": $error_handling,
    "realtime_usage": $realtime_usage,
    "storage_usage": $storage_usage
  }
}
EOF

echo "📄 Supabase validation report saved to meta-agent/state/supabase-validation-report.json"
echo "✅ Supabase validation completed"