/**
 * Frontend Error → Slack 알림 유틸리티
 *
 * 프로덕션에서만 /api/error-report로 POST 전송
 * 동일 에러(type+message) 60초 쿨다운 → 스팸 방지
 */

export interface ErrorReport {
  errorType: 'ERROR_BOUNDARY' | 'CHUNK_LOAD_ERROR';
  message: string;
  pageUrl: string;
  timestamp: string;
  digest?: string;
  stack?: string;
  userAgent?: string;
}

const COOLDOWN_MS = 60_000;
const recentErrors = new Map<string, number>();

function makeKey(report: ErrorReport): string {
  return `${report.errorType}::${report.message}`;
}

export function reportErrorToSlack(report: ErrorReport): void {
  const key = makeKey(report);
  const now = Date.now();
  const last = recentErrors.get(key);

  if (last && now - last < COOLDOWN_MS) {
    return; // 쿨다운 중 → 스킵
  }
  recentErrors.set(key, now);

  if (process.env.NODE_ENV !== 'production') {
    console.log('[ErrorReport] Dev mode — would send:', report);
    return;
  }

  // fire-and-forget
  fetch('/api/error-report', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(report),
  }).catch(() => {
    // 절대 throw 안 함
  });
}
