import { http } from "./client";
import type { Session, ViewerTokenResponse } from "./types";

/**
 * GET /api/sessions — all live sessions known to the relay's in-memory session
 * manager (active + offline-persistent). Requires an authenticated dashboard
 * JWT; any authenticated user may list.
 */
export function listSessions(signal?: AbortSignal): Promise<Session[]> {
  return http.get<Session[]>("/api/sessions", signal);
}

/**
 * POST /api/sessions/:id/viewer-token — mint a short-lived, session-scoped
 * viewer token. The server decides the access mode from the caller's
 * permissions: admin or `control` permission gets a `control` token, otherwise
 * a `view_only` token. A caller with neither `control` nor `view` gets 403.
 * The access mode is stamped into the signed token; this response only echoes
 * it. (See server/src/api/sessions.rs::mint_viewer_token.)
 */
export function mintViewerToken(
  sessionId: string,
): Promise<ViewerTokenResponse> {
  return http.post<ViewerTokenResponse>(
    `/api/sessions/${encodeURIComponent(sessionId)}/viewer-token`,
  );
}

/**
 * DELETE /api/sessions/:id — disconnect/end a live session. The relay sends a
 * Disconnect to the agent. Returns 200 on success, 404 if the session is not
 * found. Requires an authenticated dashboard JWT (not admin-gated server-side).
 */
export function endSession(sessionId: string): Promise<void> {
  return http.del<void>(`/api/sessions/${encodeURIComponent(sessionId)}`);
}
