"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.apiClientCollectionsRoutes = apiClientCollectionsRoutes;
const api_1 = require("@yinuo-ngm/api");
const errors_1 = require("@yinuo-ngm/errors");
const errors_2 = require("@yinuo-ngm/errors");
function assertProjectScope(scope, projectId) {
    if (scope === "project" && !projectId)
        throw new errors_2.GlobalError(errors_2.GlobalErrorCodes.BAD_REQUEST, "projectId is required when scope=project");
}
function now() { return Date.now(); }
async function apiClientCollectionsRoutes(fastify) {
    const api = fastify.api;
    fastify.get("/", async (req) => {
        const q = req.query;
        const scope = (q.scope ?? "project");
        assertProjectScope(scope, q.projectId);
        const collections = await api.listCollections(scope, q.projectId);
        return collections.sort((a, b) => (a.parentId ?? "").localeCompare(b.parentId ?? "") || a.order - b.order || a.name.localeCompare(b.name));
    });
    fastify.get("/bundle", async (req) => {
        const q = req.query;
        const scope = (q.scope ?? "project");
        assertProjectScope(scope, q.projectId);
        const [collections, requests] = await Promise.all([
            api.listCollections(scope, q.projectId),
            api.listRequests(scope, q.projectId),
        ]);
        const cols = (collections ?? []).sort((a, b) => (a.parentId ?? "").localeCompare(b.parentId ?? "") ||
            a.order - b.order ||
            (a.name ?? "").localeCompare(b.name ?? ""));
        const reqs = (requests ?? []).sort((a, b) => (a.collectionId ?? "").localeCompare(b.collectionId ?? "") ||
            (a.order ?? 0) - (b.order ?? 0) ||
            (a.name ?? "").localeCompare(b.name ?? ""));
        return { collections: cols, requests: reqs };
    });
    fastify.post("/", async (req) => {
        const body = req.body;
        const scope = (body.scope ?? "project");
        assertProjectScope(scope, body.projectId);
        const ts = now();
        const entity = {
            id: (0, api_1.newId)("col"),
            name: String(body.name ?? "").trim() || "New Collection",
            kind: body.kind ?? "collection",
            scope,
            nodes: [],
            projectId: scope === "project" ? body.projectId : undefined,
            parentId: body.parentId ?? null,
            order: body.order ?? ts,
            createdAt: ts,
            updatedAt: ts,
        };
        await api.saveCollection(entity, scope, body.projectId);
        return entity;
    });
    fastify.post("/:id", async (req) => {
        const params = req.params;
        const q = req.query;
        const body = req.body;
        const scope = (q.scope ?? "project");
        assertProjectScope(scope, q.projectId);
        const old = await api.getCollection(params.id, scope, q.projectId);
        if (!old) {
            throw new errors_1.ApiError(errors_1.ApiErrorCodes.API_COLLECTION_NOT_FOUND, `collection not found: ${params.id}`);
        }
        const ts = now();
        const next = {
            ...old,
            name: body.name != null ? String(body.name).trim() || old.name : old.name,
            parentId: body.parentId !== undefined ? body.parentId : old.parentId,
            order: body.order !== undefined ? Number(body.order) : old.order,
            updatedAt: ts,
        };
        await api.saveCollection(next, scope, q.projectId);
        return next;
    });
    fastify.delete("/:id", async (req) => {
        const params = req.params;
        const q = req.query;
        const scope = (q.scope ?? "project");
        assertProjectScope(scope, q.projectId);
        const allCols = await api.listCollections(scope, q.projectId);
        const hasChildCol = allCols.some(c => (c.parentId ?? null) === params.id);
        if (hasChildCol) {
            throw new errors_1.ApiError(errors_1.ApiErrorCodes.API_COLLECTION_NOT_EMPTY, "collection has child collections");
        }
        const reqs = await api.listRequests(scope, q.projectId);
        const hasReq = reqs.some((r) => (r.collectionId ?? null) === params.id);
        if (hasReq) {
            throw new errors_1.ApiError(errors_1.ApiErrorCodes.API_COLLECTION_NOT_EMPTY, "collection has requests");
        }
        await api.deleteCollection(params.id, scope, q.projectId);
        return { ok: true };
    });
}
