import { supabase } from '@/integrations/supabase/client';
import { logCallLogAudit } from '@/lib/callLogAuditLogger';

/**
 * Handles the actual insertion of call logs after validation.
 */
export async function processCallLogImport(records, user) {
  if (!records || records.length === 0) return { success: true, count: 0 };

  const recordsToInsert = records.map(r => ({
    ...r,
    caller: user.id,
    created_at: r.created_at || new Date().toISOString(),
    updated_at: new Date().toISOString()
  }));

  try {
    const { error } = await supabase.from('call_logs').insert(recordsToInsert);
    if (error) throw error;

    await logCallLogAudit({
      userId: user.id,
      action: 'IMPORT_CALLLOG_SUCCESS',
      status: 'SUCCESS',
      details: { count: recordsToInsert.length, timestamp: new Date().toISOString() }
    });

    return { success: true, count: recordsToInsert.length };
  } catch (err) {
    console.error('Import failed:', err);
    await logCallLogAudit({
      userId: user.id,
      action: 'IMPORT_CALLLOG_FAILURE',
      status: 'FAILURE',
      details: { error: err.message }
    });
    throw err;
  }
}
