/**
 * Test script to reproduce Supabase audit log sync error
 */
import { PrismaClient } from './lib/generated/prisma/index.js';
import { createClient } from '@supabase/supabase-js';
import { createId } from '@paralleldrive/cuid2';

const prisma = new PrismaClient({
  log: ['error', 'warn'],
});

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

const supabaseAdmin = createClient(supabaseUrl, supabaseKey, {
  auth: {
    autoRefreshToken: false,
    persistSession: false
  }
});

async function testAuditLogSync() {
  try {
    console.log('Testing audit log sync to both databases...\n');

    const logId = createId();
    const testData = {
      id: logId,
      userId: 'cmhzetlhf0000c90emump3y8c',
      type: 'test_staff_login',
      action: 'Test staff login attempt',
      success: true,
      ip: '127.0.0.1',
      userAgent: 'test-script',
      metadata: { test: true },
    };

    // 1. Save to Prisma
    console.log('1. Saving to Prisma...');
    const prismaLog = await prisma.auditLog.create({
      data: testData,
    });
    console.log('✅ Saved to Prisma:', prismaLog.id);

    // 2. Save to Supabase
    console.log('\n2. Syncing to Supabase...');
    const { data, error } = await supabaseAdmin
      .from('audit_logs')
      .insert({
        id: prismaLog.id,
        user_id: prismaLog.userId || null,
        type: prismaLog.type,
        action: prismaLog.action,
        success: prismaLog.success,
        ip: prismaLog.ip,
        user_agent: prismaLog.userAgent || null,
        metadata: prismaLog.metadata || null,
      });

    if (error) {
      console.error('❌ Supabase insert error:', error);
      throw error;
    }

    console.log('✅ Synced to Supabase');

    // Cleanup
    console.log('\n3. Cleaning up test data...');
    await prisma.auditLog.delete({ where: { id: logId } });
    await supabaseAdmin.from('audit_logs').delete().eq('id', logId);
    console.log('✅ Cleanup complete');

    console.log('\n✅ All tests passed - audit log sync works!');
  } catch (error) {
    console.error('\n❌ Error:', error.message);
    console.error('\nFull error:', error);
  } finally {
    await prisma.$disconnect();
  }
}

testAuditLogSync();
