import { summarizeCollectionFields } from '../collection-introspection.js';
import { generateToken as generateCsrfToken } from '../../security/csrf.js';
import { generateOpenAPISpec } from '../openapi.js';
import { getActuateConfig } from '../../config/runtime.js';
import { json, errorResponse } from '../route-helpers.js';
export function registerMetaRoutes(router) {
    // ---------------------------------------------------------------------------
    // CSRF token endpoint
    // ---------------------------------------------------------------------------
    router.get('/auth/csrf', async () => {
        const token = await generateCsrfToken();
        const isProduction = process.env.NODE_ENV === 'production';
        const cookieFlags = [`actuate_csrf=${token}`, 'Path=/', 'SameSite=Lax', 'Max-Age=86400'];
        if (isProduction)
            cookieFlags.push('Secure');
        const response = json({ data: { token } });
        response.headers.set('Set-Cookie', cookieFlags.join('; '));
        return response;
    });
    // ---------------------------------------------------------------------------
    // OpenAPI spec
    // ---------------------------------------------------------------------------
    router.get('/openapi.json', async () => {
        const config = getActuateConfig();
        if (!config)
            return errorResponse('CMS not configured', 500);
        const spec = generateOpenAPISpec(config);
        return new Response(JSON.stringify(spec, null, 2), {
            status: 200,
            headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },
        });
    });
    // ---------------------------------------------------------------------------
    // Collection discovery (Phase 7 PR F)
    //
    // Lightweight enumeration sourced directly from `getActuateConfig()` so
    // agents and the MCP server's `list_collections` tool don't depend on
    // OpenAPI spec generation succeeding. OpenAPI is still the source of
    // truth for full per-field JSON Schemas; this endpoint trades depth
    // for reliability and surfaces just enough metadata for the agent to
    // plan a follow-up call (create_document, list_documents, etc.).
    //
    // Auth: unauthenticated, like /openapi.json — the response contains
    // only schema-shape metadata that is already public via OpenAPI.
    // ---------------------------------------------------------------------------
    router.get('/collections', async () => {
        const config = getActuateConfig();
        if (!config)
            return errorResponse('CMS not configured', 500);
        const collections = Object.entries(config.collections ?? {}).map(([slug, def]) => {
            // Reduce each field to `{ name, type, required }` plus, where present,
            // the relationship target, select options, and (for `array`/`blocks`)
            // the nested subfield schema — enough for the agent to plan a deep
            // create/update AND resolve relationship fields (WS-B4 + WS-C C2)
            // without sending the full validator. See collection-introspection.ts.
            const fieldSummary = summarizeCollectionFields(def?.fields);
            return {
                slug,
                labels: def?.labels ?? { singular: slug, plural: slug },
                type: def?.type ?? 'page',
                urlPrefix: def?.urlPrefix ?? slug,
                hidden: def?.admin?.hidden === true,
                // Surface the admin metadata the Posts area needs to render
                // type tabs / cards (description, icon, accent color, group).
                // None are sensitive — they all already live on the public
                // collection definition the admin client receives via props.
                description: def?.admin?.description ?? null,
                icon: def?.admin?.icon ?? null,
                color: def?.admin?.color ?? null,
                group: def?.admin?.group ?? null,
                excludeFromPostsAggregate: def?.admin?.excludeFromPostsAggregate === true,
                fieldCount: fieldSummary.length,
                fields: fieldSummary,
            };
        });
        return json({ data: collections });
    });
    router.get('/docs', async () => {
        const html = `<!DOCTYPE html>
<html>
<head>
  <title>Actuate CMS API Reference</title>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
  <script id="api-reference" data-url="/api/cms/openapi.json"></script>
  <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
</body>
</html>`;
        return new Response(html, {
            status: 200,
            headers: { 'Content-Type': 'text/html; charset=utf-8' },
        });
    });
}
//# sourceMappingURL=meta.js.map