// 백엔드 FastAPI 클라이언트. 동일 출처 /api (dev=vite proxy, prod=nginx proxy).
import type { CrowdStats, Leaderboard, Match, ModelName } from "./types";
import type { Lang } from "./i18n";

const BASE = import.meta.env.VITE_API_BASE || "/api";

async function http<T>(path: string, init?: RequestInit): Promise<T> {
  const res = await fetch(`${BASE}${path}`, {
    headers: { "Content-Type": "application/json", ...(init?.headers || {}) },
    ...init,
  });
  if (!res.ok) {
    let detail = res.statusText;
    try {
      const body = await res.json();
      detail = body.detail || detail;
    } catch {
      /* noop */
    }
    throw new ApiError(res.status, detail);
  }
  return res.json() as Promise<T>;
}

export class ApiError extends Error {
  constructor(
    public status: number,
    public detail: string,
  ) {
    super(detail);
  }
}

export function listMatches(lang: Lang): Promise<Match[]> {
  return http<Match[]>(`/matches?lang=${lang}`);
}

export function getMatch(matchId: string, lang: Lang): Promise<Match> {
  return http<Match>(`/matches/${matchId}?lang=${lang}`);
}

export interface SubmitResult {
  ok: boolean;
  predictionId: string;
  matchedModels: ModelName[];
  exactMatch: boolean;
  crowd: CrowdStats;
}

export function submitPrediction(body: {
  matchId: string;
  deviceId: string;
  outcome: string;
  scoreA: number;
  scoreB: number;
  email?: string;
  notify: boolean;
}): Promise<SubmitResult> {
  return http<SubmitResult>(`/predictions`, {
    method: "POST",
    body: JSON.stringify(body),
  });
}

export function getLeaderboard(): Promise<Leaderboard> {
  return http<Leaderboard>(`/leaderboard`);
}

// 방문 기록 (하루 1기기 1회 집계). 실패는 무시(fire-and-forget).
export function recordVisit(): void {
  void http(`/visit`, {
    method: "POST",
    body: JSON.stringify({ deviceId: getDeviceId() }),
  }).catch(() => {});
}

// ── 비로그인 식별: deviceId (localStorage 영속) ──
const DEVICE_KEY = "tp_device_id";
export function getDeviceId(): string {
  let id = localStorage.getItem(DEVICE_KEY);
  if (!id) {
    id =
      typeof crypto !== "undefined" && crypto.randomUUID
        ? crypto.randomUUID()
        : `dev-${Date.now()}-${Math.random().toString(36).slice(2)}`;
    localStorage.setItem(DEVICE_KEY, id);
  }
  return id;
}

// 경기별 공유 딥링크
export function matchUrl(matchId: string): string {
  return `${window.location.origin}/match/${matchId}`;
}
