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

export async function logExpenseAudit({ userId, action, status, details }) {
  try {
    const { error } = await supabase.from('notification_logs').insert([
      {
        type: 'expense_audit',
        recipient: 'system',
        subject: `Expense 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 expense audit log:', error);
    }
  } catch (err) {
    console.error('Exception writing expense audit log:', err);
  }
}

export async function getExpenseAuditLogs({ limit = 50, action = null } = {}) {
  try {
    let query = supabase
      .from('notification_logs')
      .select('*')
      .eq('type', 'expense_audit')
      .order('created_at', { ascending: false })
      .limit(limit);

    const { data, error } = await query;
    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 audit logs:', err);
    return [];
  }
}
