/**
 * 백엔드 인증 API 클라이언트.
 * - JWT 쿠키 기반 (credentials: include)
 * - 로그인/로그아웃/세션 조회
 */

const API_BASE = import.meta.env.VITE_API_URL ?? '/api';

export interface MenuConfigItem {
  menuCd: string;
  parentMenuCd: string | null;
  menuType: 'ITEM' | 'GROUP' | 'DIVIDER';
  urlPath: string | null;
  rsrcCd: string | null;
  componentKey: string | null;
  icon: string | null;
  labelKey: string | null;
  dividerLabel: string | null;
  menuLevel: number;
  sortOrd: number;
  useYn: string;
  /** DB i18n SSOT: {"ko":"종합 상황판","en":"Dashboard"} */
  labels: Record<string, string>;
}

export interface BackendUser {
  id: string;
  account: string;
  name: string;
  rank: string | null;
  email: string | null;
  status: string;
  authProvider: string;
  roles: string[];
  /** rsrcCd → operCd[] (READ/CREATE/UPDATE/DELETE/EXPORT) */
  permissions: Record<string, string[]>;
  /** DB 메뉴 설정 SSOT */
  menuConfig: MenuConfigItem[];
}

export class LoginError extends Error {
  constructor(public readonly reason: string) {
    super(reason);
  }
}

export async function loginApi(account: string, password: string): Promise<BackendUser> {
  const res = await fetch(`${API_BASE}/auth/login`, {
    method: 'POST',
    credentials: 'include',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ account, password }),
  });
  if (!res.ok) {
    let reason = `HTTP_${res.status}`;
    try {
      const body = await res.json();
      if (body?.reason) reason = body.reason;
    } catch {
      // ignore
    }
    throw new LoginError(reason);
  }
  return res.json();
}

export async function logoutApi(): Promise<void> {
  await fetch(`${API_BASE}/auth/logout`, {
    method: 'POST',
    credentials: 'include',
  });
}

export async function fetchMe(): Promise<BackendUser | null> {
  try {
    const res = await fetch(`${API_BASE}/auth/me`, {
      credentials: 'include',
    });
    if (!res.ok) return null;
    return res.json();
  } catch {
    return null;
  }
}
