/**
 * Migration Script: Sync Existing Users to Supabase
 *
 * One-time migration to sync all existing Prisma users to Supabase
 * This fixes the historical data gap and ensures dashboard has all user data
 *
 * Run with: node scripts/migrate-existing-users-to-supabase.mjs
 */

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

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');
  process.exit(1);
}

const supabase = createClient(supabaseUrl, supabaseServiceKey);

async function migrateUsers() {
  console.log('\n🔄 Starting User Migration to Supabase...\n');

  try {
    // Get all users from Prisma
    const allUsers = await prisma.users.findMany({
      orderBy: { createdAt: 'desc' }
    });

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

    let successCount = 0;
    let errorCount = 0;
    let skippedCount = 0;

    for (const user of allUsers) {
      try {
        // Check if user already exists in Supabase
        const { data: existingUser } = await supabase
          .from('users')
          .select('id')
          .eq('id', user.id)
          .single();

        if (existingUser) {
          // User exists - update with latest data
          const { error: updateError } = await supabase
            .from('users')
            .update({
              email: user.email,
              name: user.name,
              password: user.password || null,
              google_id: user.googleId || null,
              email_verified: user.emailVerified?.toISOString() || null,
              last_login_at: user.lastLoginAt?.toISOString() || null,
              last_login_ip: user.lastLoginIp || null,
              failed_attempts: user.failedAttempts || 0,
              locked_until: user.lockedUntil?.toISOString() || null,
              company_name: user.companyName || null,
              industry: user.industry || null,
              company_size: user.companySize || null,
              country: user.country || null,
              city: user.city || null,
              address: user.address || null,
              phone_number: user.phoneNumber || null,
              website: user.website || null,
              selected_package: user.selectedPackage || null,
              goals: user.goals || null,
              stripe_customer_id: user.stripeCustomerId || null, // 🔑 KEY FIX
              onboarding_complete: user.onboardingComplete || false,
              updated_at: new Date().toISOString(),
            })
            .eq('id', user.id);

          if (updateError) {
            console.error(`❌ Failed to update ${user.email}:`, updateError.message);
            errorCount++;
          } else {
            console.log(`♻️  Updated ${user.email} (stripe_customer_id: ${user.stripeCustomerId || 'null'})`);
            successCount++;
          }
        } else {
          // User doesn't exist - insert
          const { error: insertError } = await supabase
            .from('users')
            .insert({
              id: user.id,
              email: user.email,
              name: user.name,
              password: user.password || null,
              google_id: user.googleId || null,
              email_verified: user.emailVerified?.toISOString() || null,
              last_login_at: user.lastLoginAt?.toISOString() || null,
              last_login_ip: user.lastLoginIp || null,
              failed_attempts: user.failedAttempts || 0,
              locked_until: user.lockedUntil?.toISOString() || null,
              company_name: user.companyName || null,
              industry: user.industry || null,
              company_size: user.companySize || null,
              country: user.country || null,
              city: user.city || null,
              address: user.address || null,
              phone_number: user.phoneNumber || null,
              website: user.website || null,
              selected_package: user.selectedPackage || null,
              goals: user.goals || null,
              stripe_customer_id: user.stripeCustomerId || null, // 🔑 KEY FIX
              onboarding_complete: user.onboardingComplete || false,
              created_at: user.createdAt.toISOString(),
              updated_at: user.updatedAt.toISOString(),
            });

          if (insertError) {
            console.error(`❌ Failed to insert ${user.email}:`, insertError.message);
            errorCount++;
          } else {
            console.log(`✅ Inserted ${user.email} (stripe_customer_id: ${user.stripeCustomerId || 'null'})`);
            successCount++;
          }
        }
      } catch (err) {
        console.error(`❌ Error processing ${user.email}:`, err.message);
        errorCount++;
      }
    }

    // Summary
    console.log('\n' + '━'.repeat(60));
    console.log('\n📊 MIGRATION SUMMARY:');
    console.log(`   Total users: ${allUsers.length}`);
    console.log(`   ✅ Successfully synced: ${successCount}`);
    console.log(`   ❌ Errors: ${errorCount}`);
    console.log(`   ⏭️  Skipped: ${skippedCount}`);

    // Verify stripe_customer_id sync
    const { data: usersWithStripe, error: stripeCheckError } = await supabase
      .from('users')
      .select('id, email, stripe_customer_id')
      .not('stripe_customer_id', 'is', null);

    if (!stripeCheckError && usersWithStripe) {
      console.log(`\n💳 Users with stripe_customer_id in Supabase: ${usersWithStripe.length}`);

      if (usersWithStripe.length > 0) {
        console.log('\nSample users with Stripe IDs:');
        usersWithStripe.slice(0, 3).forEach(u => {
          console.log(`   - ${u.email}: ${u.stripe_customer_id}`);
        });
      }
    }

    if (errorCount === 0) {
      console.log('\n✨ Migration completed successfully!');
      console.log('🎉 All user data is now available in Supabase for the dashboard!\n');
    } else {
      console.log('\n⚠️  Migration completed with some errors. Please review above.\n');
    }

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

migrateUsers();
