/**
 * 全局错误上报客户端
 *
 * 将前端运行时异常 / ErrorBoundary 捕获的错误写入 `error_logs` 表，
 * 由管理员在后台查阅。失败静默（不能让上报本身把页面搞崩）。
 */

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

export type ErrorSeverity = "info" | "warning" | "error" | "fatal";

interface ReportInput {
  message: string;
  stack?: string;
  componentStack?: string;
  severity?: ErrorSeverity;
  context?: Record<string, unknown>;
}

// 简单去重：同一条消息 5s 内只上报一次，避免风暴
const recentSignatures = new Map<string, number>();
const DEDUPE_WINDOW_MS = 5000;

function shouldDedupe(signature: string) {
  const now = Date.now();
  const last = recentSignatures.get(signature);
  if (last && now - last < DEDUPE_WINDOW_MS) return true;
  recentSignatures.set(signature, now);
  // 简单清理
  if (recentSignatures.size > 100) {
    for (const [k, t] of recentSignatures) {
      if (now - t > DEDUPE_WINDOW_MS) recentSignatures.delete(k);
    }
  }
  return false;
}

export async function reportError(input: ReportInput): Promise<void> {
  try {
    const signature = `${input.severity ?? "error"}:${input.message}`.slice(0, 200);
    if (shouldDedupe(signature)) return;

    const { data: userData } = await supabase.auth.getUser();

    // 类型暂用 any：error_logs 表刚创建，types.ts 尚未同步
    await (supabase.from as any)("error_logs").insert({
      user_id: userData?.user?.id ?? null,
      message: input.message?.slice(0, 2000) ?? "Unknown error",
      stack: input.stack?.slice(0, 8000) ?? null,
      component_stack: input.componentStack?.slice(0, 4000) ?? null,
      url: typeof window !== "undefined" ? window.location.href : null,
      user_agent: typeof navigator !== "undefined" ? navigator.userAgent : null,
      severity: input.severity ?? "error",
      context: input.context ?? {},
    });
  } catch (err) {
    // 静默：上报失败不能影响主流程
    console.warn("[errorReporter] failed to report error:", err);
  }
}
