import { fetchJson } from "./client";
import type { ApiResult, CaseRunAggregateResponse, CaseRunCasesResponse, CaseRunEventsResponse, CaseRunRunsResponse, CaseRunRunResponse } from "@/types";

export const caserunAPI = {
  cases: (): Promise<ApiResult<CaseRunCasesResponse>> => fetchJson("/v1/caserun/cases", { timeoutMs: 12000, timeoutName: "CaseRun cases" }),
  runs: (query: { status?: string; limit?: number; cursor?: string } = {}): Promise<ApiResult<CaseRunRunsResponse>> => {
    const params = new URLSearchParams();
    if (query.status) params.set("status", query.status);
    if (query.limit) params.set("limit", String(query.limit));
    if (query.cursor) params.set("cursor", query.cursor);
    const suffix = params.size ? `?${params.toString()}` : "";
    return fetchJson(`/v1/caserun/runs${suffix}`, { timeoutMs: 12000, timeoutName: "CaseRun runs" });
  },
  startRun: (caseId: string): Promise<ApiResult<CaseRunRunResponse>> => fetchJson("/v1/caserun/runs", {
    method: "POST",
    body: JSON.stringify({ caseId }),
    timeoutMs: 12000,
    timeoutName: "CaseRun start"
  }),
  run: (runId: string): Promise<ApiResult<CaseRunRunResponse>> => fetchJson(`/v1/caserun/runs/${encodeURIComponent(runId)}`, { timeoutMs: 12000, timeoutName: "CaseRun run" }),
  events: (runId: string): Promise<ApiResult<CaseRunEventsResponse>> => fetchJson(`/v1/caserun/runs/${encodeURIComponent(runId)}/events`, { timeoutMs: 12000, timeoutName: "CaseRun events" }),
  aggregate: (runId: string): Promise<ApiResult<CaseRunAggregateResponse>> => fetchJson(`/v1/caserun/runs/${encodeURIComponent(runId)}/aggregate`, { timeoutMs: 12000, timeoutName: "CaseRun aggregate" })
};
