import { http } from "./client";
import type { CreateCodeRequest, SupportCode } from "./types";

/**
 * GET /api/codes — the active support codes (server returns only `pending` and
 * `connected`, newest first is NOT guaranteed by the in-memory map, so the view
 * sorts). Requires an authenticated dashboard JWT; any authenticated user may
 * list. (See server/src/main.rs::list_codes.)
 */
export function listCodes(signal?: AbortSignal): Promise<SupportCode[]> {
  return http.get<SupportCode[]>("/api/codes", signal);
}

/**
 * POST /api/codes — generate a new one-time support code. The server creates an
 * in-memory `pending` code (and persists a durable row for the single-use
 * guard) and returns the full `SupportCode`, including the `XXX-XXX-XXX` value
 * the tech reads to the end user. `technician_name` attributes the code to the
 * operator. Requires an authenticated dashboard JWT.
 * (See server/src/main.rs::create_code.)
 */
export function createCode(body: CreateCodeRequest): Promise<SupportCode> {
  return http.post<SupportCode>("/api/codes", body);
}

/**
 * POST /api/codes/:code/cancel — revoke an un-redeemed (or connected) code. The
 * server flips a `pending`/`connected` code to `cancelled` and returns 200
 * "Code cancelled"; a code that cannot be cancelled (already completed /
 * cancelled / unknown) returns 400 "Cannot cancel code", which the typed client
 * surfaces as an ApiError with that message. Requires an authenticated JWT.
 * (See server/src/main.rs::cancel_code.)
 *
 * The path segment is the code itself; it can contain hyphens, so it is
 * URL-encoded defensively even though the unambiguous alphabet is path-safe.
 */
export function cancelCode(code: string): Promise<void> {
  return http.post<void>(`/api/codes/${encodeURIComponent(code)}/cancel`);
}
