import { PrismaClient } from '../lib/generated/prisma/index.js';

const prisma = new PrismaClient();

// Supabase credentials
const supabaseUrl = 'http://localhost:54321';
const supabaseKey = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU';

async function syncContactsFromSupabaseToPrisma() {
  console.log('🔄 Syncing contacts from Supabase to Prisma...\n');

  try {
    // 1. Get all contacts from Supabase using REST API
    const response = await fetch(`${supabaseUrl}/rest/v1/contact_submissions?select=*&order=created_at.desc`, {
      headers: {
        'apikey': supabaseKey,
        'Authorization': `Bearer ${supabaseKey}`,
      },
    });

    if (!response.ok) {
      console.error('❌ Failed to fetch from Supabase:', await response.text());
      return;
    }

    const supabaseContacts = await response.json();

    console.log(`📥 Found ${supabaseContacts.length} contacts in Supabase`);

    if (supabaseContacts.length === 0) {
      console.log('⚠️  No contacts in Supabase to sync');
      return;
    }

    // 2. Sync each contact to Prisma
    let synced = 0;
    let skipped = 0;
    let errors = 0;

    for (const contact of supabaseContacts) {
      try {
        // Check if already exists
        const existing = await prisma.contact_submissions.findUnique({
          where: { id: contact.id },
        });

        if (existing) {
          console.log(`  ⏭️  Skipping ${contact.name} (${contact.email}) - already exists`);
          skipped++;
          continue;
        }

        // Create in Prisma
        await prisma.contact_submissions.create({
          data: {
            id: contact.id,
            name: contact.name,
            email: contact.email,
            phone: contact.phone || '',
            company: contact.company || null,
            topic: contact.topic || 'other',
            message: contact.message,
            preferred_language: contact.preferred_language,
            consent: contact.consent,
            attachments: contact.attachments || [],
            ip_address: contact.ip_address || null,
            user_agent: contact.user_agent || null,
            submission_language: contact.submission_language || contact.preferred_language,
            status: contact.status || 'new',
            resolved_at: contact.resolved_at ? new Date(contact.resolved_at) : null,
            resolved_by: contact.resolved_by || null,
            notes: contact.notes || null,
            created_at: new Date(contact.created_at),
            updated_at: new Date(contact.updated_at),
          },
        });

        console.log(`  ✅ Synced: ${contact.name} (${contact.email})`);
        synced++;
      } catch (err) {
        console.error(`  ❌ Error syncing ${contact.email}:`, err.message);
        errors++;
      }
    }

    console.log('\n📊 Sync Summary:');
    console.log(`  ✅ Synced: ${synced}`);
    console.log(`  ⏭️  Skipped: ${skipped}`);
    console.log(`  ❌ Errors: ${errors}`);

    // 3. Verify
    const prismaCount = await prisma.contact_submissions.count();
    console.log(`\n🎯 Prisma now has ${prismaCount} contacts`);

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

syncContactsFromSupabaseToPrisma();
