/**
 * API functions for the ban history endpoints.
 */

import { get } from "./client";
import { ENDPOINTS } from "./endpoints";
import type {
  HistoryListResponse,
  HistoryQuery,
  IpDetailResponse,
} from "../types/history";

/**
 * Fetch a paginated list of historical bans with optional filters.
 */
export async function fetchHistory(
  query: HistoryQuery = {},
): Promise<HistoryListResponse> {
  const params = new URLSearchParams();
  if (query.range) params.set("range", query.range);
  if (query.origin) params.set("origin", query.origin);
  if (query.jail) params.set("jail", query.jail);
  if (query.ip) params.set("ip", query.ip);
  if (query.source) params.set("source", query.source);
  if (query.page !== undefined) params.set("page", String(query.page));
  if (query.page_size !== undefined)
    params.set("page_size", String(query.page_size));

  const qs = params.toString();
  const url = qs
    ? `${ENDPOINTS.history}?${qs}`
    : ENDPOINTS.history;
  return get<HistoryListResponse>(url);
}

/**
 * Fetch the full ban history for a single IP address.
 *
 * @returns null when the server returns 404 (no history for this IP).
 */
export async function fetchIpHistory(ip: string): Promise<IpDetailResponse | null> {
  try {
    return await get<IpDetailResponse>(ENDPOINTS.historyIp(ip));
  } catch (err: unknown) {
    if (
      typeof err === "object" &&
      err !== null &&
      "status" in err &&
      (err as { status: number }).status === 404
    ) {
      return null;
    }
    throw err;
  }
}
