/**
 * CMS API client. All calls go to /api/v1 on this origin, which next.config.ts
 * rewrites to the real API host (see API_ORIGIN).
 */

export const API_BASE = "/api/v1";

export class ApiError extends Error {
  constructor(
    public status: number,
    message: string,
    /** Validation messages, e.g. "content.ctas.0.href: href must be …". */
    public errors: string[] = [],
  ) {
    super(message);
    this.name = "ApiError";
  }
}

export type AdminUser = { id: string; email: string; name: string; role: "super_admin" | "admin" | (string & {}); lastLoginAt: string | null };
type LoginData = { accessToken: string; tokenType: "Bearer"; expiresIn: number; user: AdminUser };
export type Paged<T> = { data: T[]; meta: { page: number; limit: number; total: number; totalPages: number } };

/* ------------------------------------------------------------------ */
/* Session (access token in memory only)                               */
/* ------------------------------------------------------------------ */

let accessToken: string | null = null;
let onSessionLost: (() => void) | null = null;

export const setAccessToken = (t: string | null) => {
  accessToken = t;
};
export const getAccessToken = () => accessToken;
/** Called when a refresh fails mid-session (AuthProvider signs the user out). */
export const setSessionLostHandler = (fn: (() => void) | null) => {
  onSessionLost = fn;
};

/**
 * Refresh tokens are single-use and reusing one revokes the whole session, so
 * every caller must share one in-flight refresh request.
 */
let refreshing: Promise<LoginData | null> | null = null;
export function refreshSession(): Promise<LoginData | null> {
  refreshing ??= (async () => {
    try {
      const res = await fetch(`${API_BASE}/auth/refresh`, { method: "POST", credentials: "same-origin" });
      if (!res.ok) return null;
      const json = (await res.json()) as { data: LoginData };
      accessToken = json.data.accessToken;
      return json.data;
    } catch {
      return null;
    } finally {
      refreshing = null;
    }
  })();
  return refreshing;
}

/* ------------------------------------------------------------------ */
/* Requests                                                            */
/* ------------------------------------------------------------------ */

type Query = Record<string, string | number | boolean | undefined | null>;
type Opts = { method?: string; body?: unknown; query?: Query; auth?: boolean };

const qs = (q?: Query) => {
  if (!q) return "";
  const p = new URLSearchParams();
  for (const [k, v] of Object.entries(q)) if (v !== undefined && v !== null && v !== "") p.set(k, String(v));
  const s = p.toString();
  return s ? `?${s}` : "";
};

async function send(path: string, { method = "GET", body, query, auth = true }: Opts) {
  const headers: Record<string, string> = {};
  if (body !== undefined) headers["Content-Type"] = "application/json";
  if (auth && accessToken) headers.Authorization = `Bearer ${accessToken}`;
  return fetch(`${API_BASE}${path}${qs(query)}`, {
    method,
    headers,
    body: body === undefined ? undefined : JSON.stringify(body),
    credentials: "same-origin",
    cache: "no-store",
  });
}

async function toError(res: Response): Promise<ApiError> {
  try {
    const j = (await res.json()) as { message?: string; errors?: string[] };
    return new ApiError(res.status, j.message || res.statusText, j.errors ?? []);
  } catch {
    return new ApiError(res.status, res.status === 429 ? "Too many requests. Wait a minute and try again." : res.statusText || "Request failed");
  }
}

/** Returns `data` from `{ success, data }`, or undefined for 204. */
export async function api<T>(path: string, opts: Opts = {}): Promise<T> {
  let res = await send(path, opts);
  if (res.status === 401 && opts.auth !== false) {
    const refreshed = await refreshSession();
    if (!refreshed) {
      onSessionLost?.();
      throw await toError(res);
    }
    res = await send(path, opts);
  }
  if (!res.ok) throw await toError(res);
  if (res.status === 204) return undefined as T;
  const json = (await res.json()) as { data: T };
  return json.data;
}

/** Same as api() but keeps `meta` for paginated lists. */
export async function apiPaged<T>(path: string, query: Query): Promise<Paged<T>> {
  let res = await send(path, { query });
  if (res.status === 401) {
    if (!(await refreshSession())) {
      onSessionLost?.();
      throw await toError(res);
    }
    res = await send(path, { query });
  }
  if (!res.ok) throw await toError(res);
  return (await res.json()) as Paged<T>;
}

/* ------------------------------------------------------------------ */
/* Auth endpoints                                                      */
/* ------------------------------------------------------------------ */

/**
 * `clientRegion` is the region the API detected for this browser (GET /public/locale).
 * The API records it for its login location history: as a cross-check, or as the
 * location when no IP has a known country. `clientIp` is added on the server by
 * app/api/v1/auth/login/route.ts (a browser can't know its own public IP).
 */
export async function login(email: string, password: string, clientRegion?: string): Promise<AdminUser> {
  const body = clientRegion ? { email, password, clientRegion } : { email, password };
  const d = await api<LoginData>("/auth/login", { method: "POST", body, auth: false });
  accessToken = d.accessToken;
  return d.user;
}

export async function logout() {
  try {
    await api<void>("/auth/logout", { method: "POST", auth: false });
  } finally {
    accessToken = null;
  }
}

/** Human-readable message for any thrown value. */
export const errorMessage = (e: unknown) =>
  e instanceof ApiError ? (e.errors.length ? e.errors.join("\n") : e.message) : e instanceof Error ? e.message : "Something went wrong";

/**
 * Map server validation messages to field paths:
 * "content.ctas.0.href: href must be …" → { "ctas.0.href": "href must be …" }.
 */
export function fieldErrors(e: unknown, prefix = ""): Record<string, string> {
  const out: Record<string, string> = {};
  if (!(e instanceof ApiError)) return out;
  for (const msg of e.errors) {
    const m = /^([\w.]+):\s*(.*)$/.exec(msg);
    if (!m) continue;
    let path = m[1];
    if (prefix && path.startsWith(prefix)) path = path.slice(prefix.length);
    out[path] = out[path] ? `${out[path]}; ${m[2]}` : m[2];
  }
  return out;
}

/* ------------------------------------------------------------------ */
/* Raw authenticated fetch (e.g. multipart uploads)                    */
/* ------------------------------------------------------------------ */

/** fetch() to an API path with the bearer token and one refresh-and-retry on 401. Caller handles the body. */
export async function authedFetch(path: string, init: RequestInit): Promise<Response> {
  const go = () =>
    fetch(`${API_BASE}${path}`, {
      ...init,
      headers: { ...(init.headers as Record<string, string> | undefined), ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}) },
      credentials: "same-origin",
    });
  let res = await go();
  if (res.status === 401) {
    if (!(await refreshSession())) {
      onSessionLost?.();
      return res;
    }
    res = await go();
  }
  return res;
}
