import type { ApiSettings } from "../types";

const STORAGE_KEY = "govoplan.apiSettings";
const LEGACY_STORAGE_KEYS: string[] = [];
const SESSION_STORAGE_KEY = "govoplan.session";
const CSRF_COOKIE_NAME = import.meta.env.VITE_CSRF_COOKIE_NAME ?? "govoplan_csrf";
const RECENT_SAFE_REQUEST_TTL_MS = 750;
const MAX_RECENT_SAFE_REQUESTS = 100;
const MAX_CONDITIONAL_SAFE_REQUESTS = 200;

export const AUTH_REQUIRED_EVENT = "govoplan:auth-required";

export type AuthRequiredEventDetail = {
  path: string;
  status: number;
  message: string;
};

type RecentSafeRequest = {
  value: unknown;
  expiresAt: number;
};

type ConditionalSafeRequest = {
  value: unknown;
  etag: string;
};

const inFlightSafeRequests = new Map<string, Promise<unknown>>();
const recentSafeRequests = new Map<string, RecentSafeRequest>();
const conditionalSafeRequests = new Map<string, ConditionalSafeRequest>();
let safeRequestGeneration = 0;

export class ApiError extends Error {
  readonly status: number;
  readonly statusText: string;
  readonly body: string;

  constructor(status: number, statusText: string, body: string) {
    super(`${status} ${statusText}: ${body}`);
    this.name = "ApiError";
    this.status = status;
    this.statusText = statusText;
    this.body = body;
  }
}

export function isApiError(error: unknown, ...statuses: number[]): error is ApiError {
  return error instanceof ApiError && (statuses.length === 0 || statuses.includes(error.status));
}

/**
 * API endpoint helpers already pass paths beginning with /api/v1. The configured
 * value is therefore an origin only. Normalize legacy values that included the
 * API prefix so old localStorage settings cannot produce /api/v1/api/v1 URLs.
 */
export function normalizeApiBaseUrl(value: string): string {
  const trimmed = value.trim();
  if (!trimmed || trimmed === "." || trimmed === "./") return "";

  const withoutTrailingSlash = trimmed.replace(/\/+$/, "");
  const withoutApiPrefix = withoutTrailingSlash.replace(/\/api(?:\/v1)?$/i, "");

  // API base is an origin, not a frontend route prefix. Path-only values such
  // as /a or . are stale/invalid local settings and would bypass Vite's /api
  // proxy by producing /a/api/v1/... requests.
  if (withoutApiPrefix.startsWith("/") && !withoutApiPrefix.startsWith("//")) {
    return "";
  }

  return withoutApiPrefix;
}

export function apiUrl(settings: ApiSettings, path: string): string {
  const baseUrl = normalizeApiBaseUrl(settings.apiBaseUrl);
  const normalizedPath = path.startsWith("/") ? path : `/${path}`;
  return baseUrl ? `${baseUrl}${normalizedPath}` : normalizedPath;
}

export type ApiQueryValue = string | number | boolean | null | undefined;
export type ApiQueryParams = Record<string, ApiQueryValue | readonly ApiQueryValue[]>;

function queryValue(value: ApiQueryValue): string | null {
  if (value === null || value === undefined || value === "") return null;
  return String(value);
}

export function apiQuery(params: ApiQueryParams = {}): string {
  const search = new URLSearchParams();
  for (const [key, rawValue] of Object.entries(params)) {
    const values = Array.isArray(rawValue) ? rawValue : [rawValue];
    for (const value of values) {
      const normalized = queryValue(value);
      if (normalized !== null) search.append(key, normalized);
    }
  }
  const query = search.toString();
  return query ? `?${query}` : "";
}

export function apiPath(path: string, params: ApiQueryParams = {}): string {
  const query = apiQuery(params);
  if (!query) return path;
  return path.includes("?") ? `${path}&${query.slice(1)}` : `${path}${query}`;
}

export async function apiGetList<TItem, K extends string>(
  settings: ApiSettings,
  path: string,
  key: K,
  params: ApiQueryParams = {}
): Promise<TItem[]> {
  const response = await apiFetch<Record<K, TItem[] | null | undefined>>(settings, apiPath(path, params));
  return response[key] ?? [];
}

export function apiPost<TResponse>(settings: ApiSettings, path: string, init: Omit<RequestInit, "method"> = {}): Promise<TResponse> {
  return apiFetch<TResponse>(settings, path, { ...init, method: "POST" });
}

export function apiPostJson<TResponse, TPayload = unknown>(
  settings: ApiSettings,
  path: string,
  payload: TPayload,
  init: Omit<RequestInit, "method" | "body"> = {}
): Promise<TResponse> {
  return apiPost<TResponse>(settings, path, { ...init, body: JSON.stringify(payload) });
}

export function loadApiSettings(): ApiSettings {
  const storedBaseUrl = loadStoredSetting("baseUrl");
  const storedApiKey = sessionStorage.getItem(`${SESSION_STORAGE_KEY}.apiKey`);
  const configuredBaseUrl = storedBaseUrl !== null ? storedBaseUrl : import.meta.env.VITE_API_BASE_URL ?? "";
  const apiBaseUrl = normalizeApiBaseUrl(configuredBaseUrl);

  // Repair legacy values once loaded, while keeping an empty value for same-origin use.
  if (storedBaseUrl !== null && storedBaseUrl !== apiBaseUrl) {
    localStorage.setItem(`${STORAGE_KEY}.baseUrl`, apiBaseUrl);
  }
  clearLegacyStoredSetting("baseUrl");
  clearLegacyStoredSetting("apiKey");
  localStorage.removeItem(`${STORAGE_KEY}.apiKey`);

  localStorage.removeItem(`${STORAGE_KEY}.accessToken`);
  sessionStorage.removeItem(`${SESSION_STORAGE_KEY}.accessToken`);

  return {
    // Empty base URL means "same origin". In Vite dev, /api is proxied to FastAPI.
    apiBaseUrl,
    apiKey: storedApiKey || "",
    accessToken: ""
  };
}

export function saveApiSettings(settings: ApiSettings): void {
  localStorage.setItem(`${STORAGE_KEY}.baseUrl`, normalizeApiBaseUrl(settings.apiBaseUrl));
  if (settings.apiKey) {
    sessionStorage.setItem(`${SESSION_STORAGE_KEY}.apiKey`, settings.apiKey);
  } else {
    sessionStorage.removeItem(`${SESSION_STORAGE_KEY}.apiKey`);
  }
  clearLegacyStoredSetting("baseUrl");
  clearLegacyStoredSetting("apiKey");
  localStorage.removeItem(`${STORAGE_KEY}.apiKey`);
  localStorage.removeItem(`${STORAGE_KEY}.accessToken`);
  sessionStorage.removeItem(`${SESSION_STORAGE_KEY}.accessToken`);
}

export function clearAccessToken(): void {
  sessionStorage.removeItem(`${SESSION_STORAGE_KEY}.accessToken`);
  localStorage.removeItem(`${STORAGE_KEY}.accessToken`);
}

function loadStoredSetting(name: string): string | null {
  const keys = [STORAGE_KEY, ...LEGACY_STORAGE_KEYS];
  for (const key of keys) {
    const value = localStorage.getItem(`${key}.${name}`);
    if (value !== null) return value;
  }
  return null;
}

function clearLegacyStoredSetting(name: string): void {
  for (const key of LEGACY_STORAGE_KEYS) {
    localStorage.removeItem(`${key}.${name}`);
  }
}


function readCookie(name: string): string {
  const prefix = `${encodeURIComponent(name)}=`;
  return document.cookie.
  split(";").
  map((part) => part.trim()).
  find((part) => part.startsWith(prefix))?.
  slice(prefix.length) ?? "";
}

export function csrfToken(): string {
  const value = readCookie(CSRF_COOKIE_NAME);
  return value ? decodeURIComponent(value) : "";
}

function isUnsafeMethod(method?: string): boolean {
  const normalized = (method || "GET").toUpperCase();
  return !["GET", "HEAD", "OPTIONS", "TRACE"].includes(normalized);
}

function canReuseSafeRequest(method: string, init?: RequestInit): boolean {
  return (method === "GET" || method === "HEAD") &&
  !init?.body &&
  !init?.signal &&
  init?.cache !== "no-store" &&
  init?.cache !== "reload";
}

function requestHeadersKey(headers: Headers): string {
  return [...headers.entries()].
  sort(([left], [right]) => left.localeCompare(right)).
  map(([key, value]) => `${key}:${value}`).
  join("\n");
}

function safeRequestKey(url: string, method: string, headers: Headers, init?: RequestInit): string {
  return [
  method,
  url,
  init?.credentials ?? "include",
  init?.mode ?? "",
  init?.redirect ?? "",
  requestHeadersKey(headers)].
  join("\n\n");
}

function pruneRecentSafeRequests(now = Date.now()): void {
  for (const [key, entry] of recentSafeRequests) {
    if (entry.expiresAt <= now) {
      recentSafeRequests.delete(key);
    }
  }

  while (recentSafeRequests.size > MAX_RECENT_SAFE_REQUESTS) {
    const oldestKey = recentSafeRequests.keys().next().value;
    if (!oldestKey) break;
    recentSafeRequests.delete(oldestKey);
  }
}

function recentSafeResponse(key: string): unknown | undefined {
  const now = Date.now();
  const recent = recentSafeRequests.get(key);
  if (!recent) return undefined;
  if (recent.expiresAt <= now) {
    recentSafeRequests.delete(key);
    return undefined;
  }
  return recent.value;
}

function rememberSafeResponse(key: string, value: unknown): void {
  const now = Date.now();
  recentSafeRequests.set(key, { value, expiresAt: now + RECENT_SAFE_REQUEST_TTL_MS });
  pruneRecentSafeRequests(now);
}

function conditionalSafeResponse(key: string): ConditionalSafeRequest | undefined {
  const cached = conditionalSafeRequests.get(key);
  if (!cached) return undefined;
  conditionalSafeRequests.delete(key);
  conditionalSafeRequests.set(key, cached);
  return cached;
}

function rememberConditionalSafeResponse(key: string, etag: string, value: unknown): void {
  conditionalSafeRequests.delete(key);
  conditionalSafeRequests.set(key, { etag, value });
  while (conditionalSafeRequests.size > MAX_CONDITIONAL_SAFE_REQUESTS) {
    const oldestKey = conditionalSafeRequests.keys().next().value;
    if (!oldestKey) break;
    conditionalSafeRequests.delete(oldestKey);
  }
}

function clearSafeRequestCaches(): void {
  safeRequestGeneration += 1;
  inFlightSafeRequests.clear();
  recentSafeRequests.clear();
  conditionalSafeRequests.clear();
}

export function authHeaders(settings: ApiSettings): Headers {
  const headers = new Headers();
  if (settings.accessToken) {
    headers.set("Authorization", `Bearer ${settings.accessToken}`);
  } else if (settings.apiKey) {
    headers.set("X-API-Key", settings.apiKey);
  }
  return headers;
}

function shouldNotifyAuthRequired(path: string): boolean {
  const normalized = path.split("?", 1)[0].replace(/\/+$/, "");
  return !normalized.endsWith("/auth/login");
}

function notifyAuthRequired(path: string): void {
  if (typeof window === "undefined" || !shouldNotifyAuthRequired(path)) return;
  const detail: AuthRequiredEventDetail = {
    path,
    status: 401,
    message: "i18n:govoplan-core.your_session_has_expired_sign_in_again_to_contin.4cc6a1b3"
  };
  window.dispatchEvent(new CustomEvent<AuthRequiredEventDetail>(AUTH_REQUIRED_EVENT, { detail }));
}

function authExpiredError(statusText: string): ApiError {
  return new ApiError(401, statusText || "i18n:govoplan-core.unauthorized.740b8315", "i18n:govoplan-core.your_session_has_expired_sign_in_again_to_contin.4cc6a1b3");
}

export async function apiFetch<T>(settings: ApiSettings, path: string, init?: RequestInit): Promise<T> {
  const headers = new Headers(init?.headers || {});
  const method = (init?.method || "GET").toUpperCase();

  if (!(init?.body instanceof FormData) && !headers.has("Content-Type")) {
    headers.set("Content-Type", "application/json");
  }

  for (const [key, value] of authHeaders(settings)) {
    headers.set(key, value);
  }

  const csrf = csrfToken();
  if (csrf && isUnsafeMethod(method) && !headers.has("X-CSRF-Token")) {
    headers.set("X-CSRF-Token", csrf);
  }

  if (isUnsafeMethod(method)) {
    clearSafeRequestCaches();
  }

  const url = apiUrl(settings, path);
  const reusableSafeRequest = canReuseSafeRequest(method, init);
  const cacheKey = reusableSafeRequest ? safeRequestKey(url, method, headers, init) : null;

  async function runFetch(): Promise<T> {
    const fetchHeaders = new Headers(headers);
    const conditional = cacheKey ? conditionalSafeResponse(cacheKey) : undefined;
    if (conditional && !fetchHeaders.has("If-None-Match")) {
      fetchHeaders.set("If-None-Match", conditional.etag);
    }
    const fetchInit = { ...init, headers: fetchHeaders, credentials: init?.credentials ?? "include" };
    const response = await fetch(url, fetchInit);

    if (response.status === 304 && cacheKey && conditional) {
      rememberSafeResponse(cacheKey, conditional.value);
      return conditional.value as T;
    }

    if (!response.ok) {
      const text = await response.text();
      if (response.status === 401 && shouldNotifyAuthRequired(path)) {
        notifyAuthRequired(path);
        throw authExpiredError(response.statusText);
      }
      throw new ApiError(response.status, response.statusText, text);
    }

    if (response.status === 204) {
      if (cacheKey) conditionalSafeRequests.delete(cacheKey);
      return undefined as T;
    }

    const contentType = response.headers.get("content-type") || "";
    let value: T;
    if (!contentType.includes("application/json")) {
      value = (await response.text()) as T;
    } else {
      value = (await response.json()) as T;
    }

    const etag = response.headers.get("etag");
    if (cacheKey && etag) {
      rememberConditionalSafeResponse(cacheKey, etag, value);
    } else if (cacheKey) {
      conditionalSafeRequests.delete(cacheKey);
    }
    return value;
  }

  if (!reusableSafeRequest || !cacheKey) {
    return runFetch();
  }

  const requestGeneration = safeRequestGeneration;
  const recent = recentSafeResponse(cacheKey);
  if (recent !== undefined) {
    return recent as T;
  }

  const existing = inFlightSafeRequests.get(cacheKey);
  if (existing) {
    return existing as Promise<T>;
  }

  const request = runFetch().
  then((value) => {
    if (requestGeneration === safeRequestGeneration) {
      rememberSafeResponse(cacheKey, value);
    }
    return value;
  }).
  finally(() => {
    if (inFlightSafeRequests.get(cacheKey) === request) {
      inFlightSafeRequests.delete(cacheKey);
    }
  });
  inFlightSafeRequests.set(cacheKey, request);
  return request;
}


export async function apiDownload(settings: ApiSettings, path: string, filename: string): Promise<void> {
  const response = await fetch(apiUrl(settings, path), { headers: authHeaders(settings), credentials: "include" });
  if (!response.ok) {
    const text = await response.text();
    if (response.status === 401 && shouldNotifyAuthRequired(path)) {
      notifyAuthRequired(path);
      throw authExpiredError(response.statusText);
    }
    throw new ApiError(response.status, response.statusText, text);
  }
  const blob = await response.blob();
  const url = URL.createObjectURL(blob);
  const anchor = document.createElement("a");
  anchor.href = url;
  anchor.download = filename;
  document.body.appendChild(anchor);
  anchor.click();
  anchor.remove();
  URL.revokeObjectURL(url);
}
