import { http } from "./client";
import type {
  CreatedKey,
  DeleteMachineParams,
  DeleteMachineResponse,
  KeyMetadata,
  Machine,
  MachineHistory,
} from "./types";

/** GET /api/machines — the real machines endpoint (NOT /api/sessions). */
export function listMachines(signal?: AbortSignal): Promise<Machine[]> {
  return http.get<Machine[]>("/api/machines", signal);
}

/** GET /api/machines/:agent_id — single machine. */
export function getMachine(agentId: string): Promise<Machine> {
  return http.get<Machine>(`/api/machines/${encodeURIComponent(agentId)}`);
}

/** GET /api/machines/:agent_id/history — past sessions + events. */
export function getMachineHistory(
  agentId: string,
  signal?: AbortSignal,
): Promise<MachineHistory> {
  return http.get<MachineHistory>(
    `/api/machines/${encodeURIComponent(agentId)}/history`,
    signal,
  );
}

/** DELETE /api/machines/:agent_id — remove a machine, optionally uninstall/export. */
export function deleteMachine(
  agentId: string,
  params: DeleteMachineParams = {},
): Promise<DeleteMachineResponse> {
  const qs = new URLSearchParams();
  if (params.uninstall) qs.set("uninstall", "true");
  if (params.export) qs.set("export", "true");
  const suffix = qs.toString() ? `?${qs.toString()}` : "";
  return http.del<DeleteMachineResponse>(
    `/api/machines/${encodeURIComponent(agentId)}${suffix}`,
  );
}

// --- Admin: per-agent keys --------------------------------------------------

/** GET /api/machines/:agent_id/keys — list key metadata (admin only). */
export function listMachineKeys(agentId: string): Promise<KeyMetadata[]> {
  return http.get<KeyMetadata[]>(
    `/api/machines/${encodeURIComponent(agentId)}/keys`,
  );
}

/**
 * POST /api/machines/:agent_id/keys — mint a new per-agent key (admin only).
 * The plaintext `key` is returned ONCE in the response — never again.
 */
export function createMachineKey(agentId: string): Promise<CreatedKey> {
  return http.post<CreatedKey>(
    `/api/machines/${encodeURIComponent(agentId)}/keys`,
  );
}

/** DELETE /api/machines/:agent_id/keys/:key_id — revoke a key (admin only). */
export function revokeMachineKey(
  agentId: string,
  keyId: string,
): Promise<void> {
  return http.del<void>(
    `/api/machines/${encodeURIComponent(agentId)}/keys/${encodeURIComponent(keyId)}`,
  );
}
