import type { HistoryResponse, RuntimeMode } from "../../shared/api";
import type { ProbeStore } from "../checker/store";

import { jsonResponse, mapCheckResult } from "../helpers";
import { validatePagination, validateTargetId, validateTimeRange } from "../middleware";

export function handleHistory(idStr: string, url: URL, store: ProbeStore, mode: RuntimeMode): Response {
  const idResult = validateTargetId(idStr, mode);
  if (idResult instanceof Response) return idResult;

  const target = store.getTargetById(idResult.id);
  if (!target) {
    return jsonResponse({ error: "Target not found", status: 404 } as const, { mode, status: 404 });
  }

  const timeResult = validateTimeRange(url.searchParams.get("from"), url.searchParams.get("to"), mode);
  if (timeResult instanceof Response) return timeResult;

  const pageResult = validatePagination(url.searchParams.get("page"), url.searchParams.get("pageSize"), mode);
  if (pageResult instanceof Response) return pageResult;

  const result = store.getHistory(idResult.id, timeResult.from, timeResult.to, pageResult.page, pageResult.pageSize);
  const response: HistoryResponse = {
    items: result.items.map((row) => mapCheckResult(row, target.type)),
    page: result.page,
    pageSize: result.pageSize,
    total: result.total,
  };

  return jsonResponse(response, { mode });
}
