import { customFetch } from "@/api/mutator";

type ApiResponse<T> = {
  data: T;
  status: number;
  headers: Headers;
};

export type GatewayAgentImportCandidate = {
  gateway_agent_id: string;
  gateway_agent_name: string | null;
  session_key: string | null;
  existing_agent_id: string | null;
  importable: boolean;
  inferred_board_id: string | null;
  inferred_is_board_lead: boolean;
};

export type GatewayAgentImportPreviewResponse = {
  gateway_id: string;
  discovered_count: number;
  importable_count: number;
  already_tracked_count: number;
  candidates: GatewayAgentImportCandidate[];
};

export type GatewayAgentReconcileError = {
  agent_id: string | null;
  message: string;
};

export type GatewayAgentImportReconcileSummary = {
  attempted: number;
  updated: number;
  skipped: number;
  errors: GatewayAgentReconcileError[];
};

export type GatewayAgentImportResponse = {
  gateway_id: string;
  imported_count: number;
  skipped_count: number;
  imported_agent_ids: string[];
  skipped_gateway_agent_ids: string[];
  reconcile: GatewayAgentImportReconcileSummary | null;
};

export type GatewayAgentImportRequest = {
  gateway_agent_ids: string[];
  reconcile_after_import: boolean;
  rotate_tokens: boolean;
  reset_sessions: boolean;
  force_bootstrap: boolean;
};

async function fetchJson<T>(path: string, init?: RequestInit): Promise<T> {
  const response = await customFetch<ApiResponse<T>>(path, init ?? {});
  return response.data;
}

export async function getGatewayAgentImportPreview(
  gatewayId: string,
): Promise<GatewayAgentImportPreviewResponse> {
  return fetchJson<GatewayAgentImportPreviewResponse>(
    `/api/v1/gateways/${gatewayId}/agents/import-preview`,
  );
}

export async function importGatewayAgents(
  gatewayId: string,
  payload: GatewayAgentImportRequest,
): Promise<GatewayAgentImportResponse> {
  return fetchJson<GatewayAgentImportResponse>(
    `/api/v1/gateways/${gatewayId}/agents/import`,
    {
      method: "POST",
      body: JSON.stringify(payload),
    },
  );
}
