/**
 * HTTP client for the PBPS MIS V2 API (master plan, Part G).
 * - Base path `/api/v2` (override with VITE_API_BASE).
 * - Cookie session (`credentials: "include"`) + CSRF header on writes.
 * - Errors are RFC 7807 `application/problem+json` → ApiError.
 * The same origin serves the API: Vite proxies /api in development, Nginx in production.
 */
import { ApiError, type FieldError } from "./client";

export const API_BASE: string =
  (import.meta.env["VITE_API_BASE"] as string | undefined) ?? "/api/v2";

/** Project the user is working in (set by the /p/$pid layout route). */
let currentProjectId = "1";
const watchers = new Set<() => void>();
/** Runs before the new project is shown, so nothing of the previous one stays on screen. */
export const onProjectChange = (f: () => void) => {
  watchers.add(f);
  return () => {
    watchers.delete(f);
  };
};
export const setProjectId = (pid: string) => {
  if (pid === currentProjectId) return;
  currentProjectId = pid;
  watchers.forEach((f) => f());
};
export const getProjectId = () => currentProjectId;
/** `/projects/:projectId` prefix for project-scoped resources. */
export const proj = (path = "") => `/projects/${encodeURIComponent(currentProjectId)}${path}`;

type Query = Record<string, string | number | boolean | undefined | null | string[]>;
export interface RequestOpts {
  query?: Query;
  body?: unknown;
  form?: FormData;
  idempotencyKey?: string;
  signal?: AbortSignal;
}

function qs(query?: Query): string {
  if (!query) return "";
  const p = new URLSearchParams();
  Object.entries(query).forEach(([k, v]) => {
    if (v === undefined || v === null || v === "") return;
    if (Array.isArray(v)) v.forEach((x) => p.append(k, x));
    else p.set(k, String(v));
  });
  const s = p.toString();
  return s ? `?${s}` : "";
}

function csrfToken(): string | undefined {
  if (typeof document === "undefined") return undefined;
  return /(?:^|;\s*)pbps_csrf=([^;]+)/.exec(document.cookie)?.[1];
}

interface Problem {
  title?: string;
  detail?: string;
  status?: number;
  code?: string;
  fieldErrors?: FieldError[];
  requestId?: string;
}

export async function http<T>(
  method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE",
  path: string,
  opts: RequestOpts = {},
): Promise<T> {
  const headers: Record<string, string> = { Accept: "application/json" };
  let body: BodyInit | undefined;
  if (opts.form) body = opts.form;
  else if (opts.body !== undefined) {
    headers["Content-Type"] = "application/json";
    body = JSON.stringify(opts.body);
  }
  if (method !== "GET") {
    const t = csrfToken();
    if (t) headers["X-CSRF-Token"] = t;
  }
  if (opts.idempotencyKey) headers["Idempotency-Key"] = opts.idempotencyKey;

  let res: Response;
  try {
    res = await fetch(`${API_BASE}${path}${qs(opts.query)}`, {
      method,
      headers,
      body: body ?? null,
      credentials: "include",
      ...(opts.signal ? { signal: opts.signal } : {}),
    });
  } catch {
    throw new ApiError(
      0,
      "NETWORK_ERROR",
      "Cannot reach the server. Check your connection and try again.",
    );
  }
  if (res.status === 204) return undefined as T;
  const text = await res.text();
  const data: unknown = text ? safeJson(text) : undefined;
  if (!res.ok) {
    const p = (data ?? {}) as Problem;
    throw new ApiError(
      res.status,
      p.code ?? `HTTP_${res.status}`,
      p.detail ?? p.title ?? res.statusText ?? "Request failed.",
      p.fieldErrors ?? [],
      p.requestId ?? res.headers.get("x-request-id") ?? undefined,
    );
  }
  return data as T;
}
function safeJson(t: string): unknown {
  try {
    return JSON.parse(t);
  } catch {
    return t;
  }
}

export const get = <T>(path: string, query?: Query) => http<T>("GET", path, query ? { query } : {});
export const post = <T>(path: string, body?: unknown, extra: Omit<RequestOpts, "body"> = {}) =>
  http<T>("POST", path, { ...extra, ...(body !== undefined ? { body } : {}) });
export const put = <T>(path: string, body?: unknown) =>
  http<T>("PUT", path, body !== undefined ? { body } : {});
export const patch = <T>(path: string, body?: unknown) =>
  http<T>("PATCH", path, body !== undefined ? { body } : {});
export const del = <T>(path: string) => http<T>("DELETE", path);
export const upload = <T>(path: string, form: FormData) => http<T>("POST", path, { form });

/** Stable idempotency key for one user action (double clicks reuse it). */
export const newIdempotencyKey = () =>
  typeof crypto !== "undefined" && "randomUUID" in crypto
    ? crypto.randomUUID()
    : `${Date.now()}-${Math.random()}`;

/** Reads a file with the session cookie; the server names it in Content-Disposition. */
export async function fetchFile(path: string): Promise<{ blob: Blob; name: string }> {
  let res: Response;
  try {
    res = await fetch(`${API_BASE}${path}`, { credentials: "include" });
  } catch {
    throw new ApiError(
      0,
      "NETWORK_ERROR",
      "Cannot reach the server. Check your connection and try again.",
    );
  }
  if (!res.ok) {
    const p = (safeJson(await res.text()) ?? {}) as Problem;
    throw new ApiError(
      res.status,
      p.code ?? `HTTP_${res.status}`,
      p.detail ?? "The file could not be opened.",
    );
  }
  const name =
    /filename="?([^";]+)"?/.exec(res.headers.get("content-disposition") ?? "")?.[1] ?? "download";
  const full = /filename\*=UTF-8''([^;]+)/.exec(res.headers.get("content-disposition") ?? "")?.[1];
  return { blob: await res.blob(), name: full ? decodeURIComponent(full) : name };
}
export async function downloadFile(path: string): Promise<void> {
  const { blob, name } = await fetchFile(path);
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = name;
  a.click();
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}
