/**
 * Narrow `CanvasClient` interface + the HTTP implementation over the Canvas
 * CRUD REST API. The interface is the injectable transport seam for tests
 * (mirrors `DriveClient`); the HTTP client is thin because the API already
 * returns each document as clean markdown — no conversion step.
 */
import { z } from "zod";
import { assertCanvasId } from "./ids.js";
/**
 * Parse-don't-validate boundary for the CRUD response (D0045). `revision`
 * only feeds the traceability manifest, so a missing one degrades to a
 * sentinel instead of failing the fetch.
 */
const CanvasDocumentSchema = z.object({
    _id: z.string().min(1),
    title: z.string().optional(),
    content: z.string(),
    revision: z.string().default("unknown"),
});
/** A failed Canvas CRUD request, carrying the HTTP status for dispatch. */
export class CanvasRequestError extends Error {
    status;
    constructor(message, status) {
        super(message);
        this.status = status;
        this.name = "CanvasRequestError";
    }
}
/**
 * HTTP `CanvasClient` over the Canvas CRUD REST API.
 *
 * `apiBase` is the CRUD path prefix (`…/vX/canvases/<resourceId>/assist`,
 * from `canvasApiBase`). Responses are shape-checked at this boundary so a
 * drifting API surfaces as a clear error here, not a crash downstream.
 */
export function createCanvasHttpClient(apiBase, token) {
    return {
        async getDocument(documentId) {
            assertCanvasId("documentId", documentId);
            const url = `${apiBase}/documents/${documentId}?format=markdown`;
            const response = await fetch(url, {
                headers: { Authorization: `Bearer ${token}` },
            });
            if (!response.ok) {
                const body = await response.text().catch(() => "");
                throw new CanvasRequestError(`Canvas CRUD GET ${documentId} failed with ${response.status}: ${body.slice(0, 300)}`, response.status);
            }
            // A shape mismatch is a contract violation, not an HTTP failure —
            // plain Error (no status) so it isn't recorded as a 2xx "HTTP" error.
            const parsed = CanvasDocumentSchema.safeParse(await response.json());
            if (!parsed.success) {
                throw new Error(`Canvas CRUD GET ${documentId} returned an unexpected shape: ${parsed.error.message}`);
            }
            return parsed.data;
        },
    };
}
