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

const logBuffer: any[] = [];
let channelSubscribed = false;

const logChannel = supabase.channel('global-app-logs', {
  config: { broadcast: { self: true, ack: false } },
});

logChannel.subscribe((status) => {
  console.log(`[RemoteLogger] Status do canal de log: ${status}`);
  if (status === 'SUBSCRIBED') {
    channelSubscribed = true;
    console.log(`[RemoteLogger] Inscrito com sucesso. Enviando ${logBuffer.length} logs acumulados...`);
    // Envia o buffer acumulado
    while (logBuffer.length > 0) {
      const payload = logBuffer.shift();
      logChannel.send({
        type: 'broadcast',
        event: 'log',
        payload,
      }).catch(err => {
        console.error('[RemoteLogger] Erro ao enviar log em buffer:', err);
      });
    }
  }
});

export function sendRemoteLog(level: 'info' | 'warn' | 'error', message: string, data?: any) {
  const consoleFn = level === 'error' ? console.error : level === 'warn' ? console.warn : console.log;
  consoleFn(`[RemoteLog] [${level}] ${message}`, data || '');

  const payload = {
    level,
    message,
    data: data ? JSON.parse(JSON.stringify(data)) : null,
    timestamp: new Date().toISOString(),
    userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : 'NodeJS',
  };

  if (channelSubscribed) {
    logChannel.send({
      type: 'broadcast',
      event: 'log',
      payload,
    }).catch(err => {
      console.error('[RemoteLogger] Falha ao enviar log remoto, enfileirando...', err);
      logBuffer.push(payload);
    });
  } else {
    logBuffer.push(payload);
  }
}

// Captura global de erros em tempo de execução
if (typeof window !== 'undefined') {
  window.addEventListener('error', (event) => {
    sendRemoteLog('error', `Global error: ${event.message} at ${event.filename}:${event.lineno}`, {
      colno: event.colno,
      stack: event.error?.stack,
    });
  });

  window.addEventListener('unhandledrejection', (event) => {
    sendRemoteLog('error', `Unhandled Promise rejection: ${event.reason}`, {
      reason: event.reason?.stack || event.reason,
    });
  });
}
