/**
 * Log Center integration — runtime error reporting.
 * Only active when VITE_LOG_CENTER_URL is explicitly configured.
 */

const LOG_CENTER_URL = import.meta.env.VITE_LOG_CENTER_URL || '';
const PROJECT_ID = 'video_web';

export function reportError(error: Error, context?: Record<string, unknown>) {
  if (!LOG_CENTER_URL) return;
  const stackLines = error.stack?.split('\n') || [];
  const match = stackLines[1]?.match(/at\s+.*\s+\((.+):(\d+):\d+\)/);

  const payload = {
    project_id: PROJECT_ID,
    environment: import.meta.env.MODE,
    level: 'ERROR',
    error: {
      type: error.name,
      message: error.message,
      file_path: match?.[1] || 'unknown',
      line_number: parseInt(match?.[2] || '0'),
      stack_trace: stackLines,
    },
    context: {
      url: window.location.href,
      userAgent: navigator.userAgent,
      ...context,
    },
  };

  const blob = new Blob([JSON.stringify(payload)], { type: 'application/json' });
  if (navigator.sendBeacon) {
    navigator.sendBeacon(`${LOG_CENTER_URL}/api/v1/logs/report`, blob);
  } else {
    fetch(`${LOG_CENTER_URL}/api/v1/logs/report`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
      keepalive: true,
    }).catch(() => {});
  }
}
