import { api } from "./client";

export type RuntimeStatus = {
  state: "idle" | "running" | "ready" | "degraded";
  message: string;
  trade_date?: string | null;
  observed_at?: string | null;
};

export type JobRun = {
  id: number;
  kind: string;
  requested_date: string;
  trigger: string;
  status: "running" | "completed" | "failed";
  attempt: number;
  started_at: string;
  finished_at: string | null;
  duration_ms: number | null;
  coverage: number | null;
  error_message: string;
};

export type EventRevisionInput = {
  event_type: "limit_up" | "broken" | "limit_down";
  reason: string;
  first_time: string;
  last_time: string;
  open_times: number | null;
};

export const operationsApi = {
  status(): Promise<RuntimeStatus> {
    return api.get("/operations/status");
  },
  jobs(): Promise<JobRun[]> {
    return api.get("/admin/operations/jobs");
  },
  backfill(start_date: string, end_date: string): Promise<Record<string, unknown>> {
    return api.post("/admin/operations/backfill", { start_date, end_date });
  },
  supplementEvents(date: string): Promise<Record<string, unknown>> {
    return api.post(`/admin/operations/events/supplement?date=${encodeURIComponent(date)}`);
  },
  reviseEvent(
    date: string,
    identifier: string,
    value: EventRevisionInput,
  ): Promise<Record<string, unknown>> {
    return api.put(
      `/admin/operations/events/${encodeURIComponent(date)}/${encodeURIComponent(identifier)}`,
      value,
    );
  },
  eventHistory(date: string, identifier: string): Promise<Record<string, unknown>[]> {
    return api.get(
      `/admin/operations/events/${encodeURIComponent(date)}/${encodeURIComponent(identifier)}/history`,
    );
  },
};
