/**
 * Verification Script: Check Supabase User Data Sync
 *
 * Verifies that user data is properly synced to Supabase
 * Run with: node scripts/verify-supabase-sync.mjs
 */

import { config } from 'dotenv';
config({ path: '.env.local' }); // Load .env.local file

import { PrismaClient } from '../lib/generated/prisma/index.js';
import { createClient } from '@supabase/supabase-js';

const prisma = new PrismaClient();

const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY;

if (!supabaseUrl || !supabaseServiceKey) {
  console.error('❌ Missing Supabase credentials');
  console.error('   NEXT_PUBLIC_SUPABASE_URL:', !!supabaseUrl);
  console.error('   SUPABASE_SERVICE_ROLE_KEY:', !!supabaseServiceKey);
  process.exit(1);
}

const supabase = createClient(supabaseUrl, supabaseServiceKey);

async function verifySync() {
  console.log('\n🔍 Verifying Supabase User Data Sync...\n');

  try {
    // Get recent users from Prisma
    const prismaUsers = await prisma.users.findMany({
      take: 5,
      orderBy: { createdAt: 'desc' },
      select: {
        id: true,
        email: true,
        name: true,
        stripeCustomerId: true,
        companyName: true,
        industry: true,
        selectedPackage: true,
        createdAt: true,
      }
    });

    console.log(`📊 Found ${prismaUsers.length} recent users in Prisma\n`);

    if (prismaUsers.length === 0) {
      console.log('⚠️  No users found in database yet');
      return;
    }

    // Check each user in Supabase
    let syncedCount = 0;
    let missingCount = 0;
    let hasStripeIdCount = 0;

    for (const user of prismaUsers) {
      const { data: supabaseUser, error } = await supabase
        .from('users')
        .select('*')
        .eq('id', user.id)
        .single();

      if (error || !supabaseUser) {
        console.log(`❌ User ${user.email} - NOT IN SUPABASE`);
        missingCount++;
        continue;
      }

      syncedCount++;
      console.log(`✅ User ${user.email}`);
      console.log(`   - Synced to Supabase: YES`);
      console.log(`   - stripe_customer_id (Prisma): ${user.stripeCustomerId || 'null'}`);
      console.log(`   - stripe_customer_id (Supabase): ${supabaseUser.stripe_customer_id || 'null'}`);
      console.log(`   - company_name: ${supabaseUser.company_name || 'null'}`);
      console.log(`   - industry: ${supabaseUser.industry || 'null'}`);
      console.log(`   - selected_package: ${supabaseUser.selected_package || 'null'}`);

      if (supabaseUser.stripe_customer_id) {
        hasStripeIdCount++;

        // Check for payments with this customer_id
        const { data: payments, error: paymentError } = await supabase
          .from('payments')
          .select('stripe_payment_intent_id, amount, currency, metadata')
          .eq('customer_id', supabaseUser.stripe_customer_id);

        if (payments && payments.length > 0) {
          console.log(`   - Payments: ${payments.length} found`);
          payments.forEach(p => {
            console.log(`     • ${p.stripe_payment_intent_id}: ${p.amount} ${p.currency}`);
            console.log(`       user_id in metadata: ${p.metadata?.user_id || 'MISSING'}`);
          });
        } else {
          console.log(`   - Payments: none found`);
        }
      }
      console.log('');
    }

    // Summary
    console.log('━'.repeat(60));
    console.log('\n📈 SYNC STATUS SUMMARY:');
    console.log(`   Total users checked: ${prismaUsers.length}`);
    console.log(`   ✅ Synced to Supabase: ${syncedCount}`);
    console.log(`   ❌ Missing from Supabase: ${missingCount}`);
    console.log(`   💳 Users with Stripe ID: ${hasStripeIdCount}`);

    if (missingCount > 0) {
      console.log('\n⚠️  WARNING: Some users are not synced to Supabase!');
      console.log('   This means the dual-database sync is not working correctly.');
    } else {
      console.log('\n✨ All users are properly synced to Supabase!');
    }

    // Check if there are users with stripe_customer_id
    const usersWithStripe = await prisma.users.count({
      where: {
        stripeCustomerId: { not: null }
      }
    });

    console.log(`\n💰 Users with stripe_customer_id in Prisma: ${usersWithStripe}`);

    if (usersWithStripe > 0) {
      // Verify these are also in Supabase
      const { data: supabaseUsersWithStripe, error } = await supabase
        .from('users')
        .select('id, email, stripe_customer_id')
        .not('stripe_customer_id', 'is', null);

      if (!error && supabaseUsersWithStripe) {
        console.log(`💰 Users with stripe_customer_id in Supabase: ${supabaseUsersWithStripe.length}`);

        if (supabaseUsersWithStripe.length < usersWithStripe) {
          console.log('\n⚠️  WARNING: stripe_customer_id sync mismatch!');
          console.log(`   Prisma has ${usersWithStripe} users with Stripe IDs`);
          console.log(`   Supabase has ${supabaseUsersWithStripe.length} users with Stripe IDs`);
          console.log('   The new checkout flow fix should resolve this for future signups.');
        }
      }
    }

    console.log('\n');

  } catch (error) {
    console.error('❌ Verification failed:', error);
  } finally {
    await prisma.$disconnect();
  }
}

verifySync();
