import { supabase } from '@/integrations/supabase/client';

/**
 * Logs a call log related action to the notification_logs table.
 */
export async function logCallLogAudit({ userId, action, status, details }) {
  try {
    const { error } = await supabase.from('notification_logs').insert([
      {
        type: 'call_log_audit', 
        recipient: 'system',   
        subject: `Call Log Action: ${action}`,
        status: status,
        metadata: {
          user_id: userId,
          action,
          timestamp: new Date().toISOString(),
          ...details
        },
        created_at: new Date().toISOString(),
        recipients_list: [],
        send_status: {}
      }
    ]);

    if (error) {
      console.error('Failed to write call log audit log:', error);
    }
  } catch (err) {
    console.error('Exception writing call log audit log:', err);
  }
}

/**
 * Retrieves audit logs for call logs.
 */
export async function getCallLogAuditLogs({ limit = 50 } = {}) {
  try {
    const { data, error } = await supabase
      .from('notification_logs')
      .select('*')
      .eq('type', 'call_log_audit')
      .order('created_at', { ascending: false })
      .limit(limit);

    if (error) throw error;
    
    return data.map(log => ({
      id: log.id,
      timestamp: log.created_at,
      action: log.metadata?.action,
      status: log.status,
      user_id: log.metadata?.user_id,
      details: log.metadata
    }));
  } catch (err) {
    console.error('Error fetching call log audit logs:', err);
    return [];
  }
}
