#!/usr/bin/env node
/**
 * Test Script: Verify profile updates sync to both Prisma and Supabase
 *
 * Usage: node scripts/test-account-profile-sync.mjs
 */

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

// Load environment variables
config({ path: resolve(process.cwd(), '.env.local') });
config({ path: resolve(process.cwd(), '.env') });

const prisma = new PrismaClient();
const supabase = createClient(
  process.env.NEXT_PUBLIC_SUPABASE_URL || 'http://localhost:54321',
  process.env.SUPABASE_SERVICE_ROLE_KEY
);

async function testProfileSync() {
  console.log('🧪 Testing Profile Update Sync to Both Databases\n');

  try {
    // 1. Find test user
    console.log('1️⃣ Finding test user (guqo@mailinator.com)...');
    const testUser = await prisma.users.findUnique({
      where: { email: 'guqo@mailinator.com' },
    });

    if (!testUser) {
      console.log('❌ Test user not found. Please create guqo@mailinator.com first.');
      return;
    }

    console.log(`✅ Found user: ${testUser.name} (${testUser.id})\n`);

    // 2. Check current data in both databases
    console.log('2️⃣ Checking current profile in both databases...');

    const { data: supabaseUser, error: supabaseError } = await supabase
      .from('users')
      .select('id, email, name, phone_number, company_name, avatar')
      .eq('id', testUser.id)
      .single();

    if (supabaseError) {
      console.log('⚠️  Supabase user not found, will be created on sync');
    } else {
      console.log('✅ Supabase user exists');
      console.log(`   Name: ${supabaseUser.name}`);
      console.log(`   Phone: ${supabaseUser.phone_number || 'N/A'}`);
      console.log(`   Company: ${supabaseUser.company_name || 'N/A'}`);
      console.log(`   Avatar: ${supabaseUser.avatar || 'N/A'}\n`);
    }

    // 3. Simulate profile update
    console.log('3️⃣ Simulating profile update...');
    const testPhone = `+974-TEST-${Date.now().toString().slice(-4)}`;
    const testCompany = `Test Company ${Date.now().toString().slice(-4)}`;

    const updatedUser = await prisma.users.update({
      where: { id: testUser.id },
      data: {
        phoneNumber: testPhone,
        companyName: testCompany,
      },
    });

    console.log(`✅ Updated in Prisma:`);
    console.log(`   Phone: ${updatedUser.phoneNumber}`);
    console.log(`   Company: ${updatedUser.companyName}\n`);

    // 4. Manually trigger Supabase sync (simulating what API does)
    console.log('4️⃣ Syncing to Supabase...');
    const { error: upsertError } = await supabase
      .from('users')
      .upsert({
        id: updatedUser.id,
        email: updatedUser.email,
        name: updatedUser.name,
        phone_number: updatedUser.phoneNumber,
        company_name: updatedUser.companyName,
        company_size: updatedUser.companySize,
        industry: updatedUser.industry,
        website: updatedUser.website,
        country: updatedUser.country,
        city: updatedUser.city,
        avatar: updatedUser.avatar,
        updated_at: new Date().toISOString(),
      }, {
        onConflict: 'id',
      });

    if (upsertError) {
      console.log(`❌ Supabase sync failed: ${upsertError.message}`);
      return;
    }

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

    // 5. Verify sync worked
    console.log('5️⃣ Verifying sync...');
    const { data: verifyUser, error: verifyError } = await supabase
      .from('users')
      .select('phone_number, company_name')
      .eq('id', testUser.id)
      .single();

    if (verifyError) {
      console.log(`❌ Verification failed: ${verifyError.message}`);
      return;
    }

    const phoneMatch = verifyUser.phone_number === testPhone;
    const companyMatch = verifyUser.company_name === testCompany;

    console.log(`   Phone match: ${phoneMatch ? '✅' : '❌'} (${verifyUser.phone_number})`);
    console.log(`   Company match: ${companyMatch ? '✅' : '❌'} (${verifyUser.company_name})\n`);

    if (phoneMatch && companyMatch) {
      console.log('🎉 SUCCESS: Profile updates sync correctly to both databases!\n');
    } else {
      console.log('❌ FAILED: Data mismatch between Prisma and Supabase\n');
    }

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

testProfileSync();
