/**
 * Sync options HTTP routes — per-workspace sync configuration read and write.
 *
 * GET  /workspaces/{ws}/sync/options → current SyncConfigSummary (sanitized)
 * PUT  /workspaces/{ws}/sync/options → update domainDepths (depth per domain)
 *
 * The PUT body is a partial SyncDomainOptions — only provided keys are updated.
 * Unrecognised keys are ignored. The route does NOT enable/disable sync itself
 * or change the endpoint URL; that remains env-configuration-only for security
 * (the bridge never accepts sync endpoint credentials from the browser).
 */
import { SEED_DOMAIN_IDS, SYNC_DEPTHS } from "../config/bridgeConfig.js";
import { authorizeWorkspace } from "./authGuards.js";
import { writeJson } from "./publicResponse.js";
import { readJsonBody } from "./requestParsing.js";
import { firstCapture, matchPath } from "./routeMatching.js";
import { isRecord } from "../utils/json.js";
const SYNC_OPTIONS_SCAN_OPTIONS = {
    allowedFieldNames: [
        "domainDepths",
        "enabled",
        "enabledDomains",
        "endpointConfigured",
        "intervalMs",
        "retryBudget",
        "timeoutMs",
    ],
};
export async function handleSyncOptionsRoutes(context) {
    const { app, auth, request, response, url } = context;
    const match = matchPath(url.pathname, /^\/workspaces\/([^/]+)\/sync\/options$/);
    if (!match)
        return false;
    const workspaceId = firstCapture(match);
    if (!authorizeWorkspace(response, auth, workspaceId))
        return true;
    if (request.method === "GET") {
        const summary = app.syncConfig
            ? {
                enabled: app.syncConfig.enabled,
                endpointConfigured: Boolean(app.syncConfig.endpointUrl),
                retryBudget: app.syncConfig.retryBudget,
                timeoutMs: app.syncConfig.timeoutMs,
                intervalMs: app.syncConfig.intervalMs,
                enabledDomains: SEED_DOMAIN_IDS.filter((id) => app.syncConfig.domains[id]),
                domainDepths: app.syncConfig.domainDepths,
            }
            : {
                enabled: false,
                endpointConfigured: false,
                retryBudget: 0,
                timeoutMs: 0,
                intervalMs: 0,
                enabledDomains: [],
                domainDepths: {},
            };
        writeJson(response, 200, summary, {
            surface: "sync.options",
            scanOptions: SYNC_OPTIONS_SCAN_OPTIONS,
        });
        return true;
    }
    if (request.method === "PUT") {
        try {
            const body = await readJsonBody(request);
            if (!isRecord(body) || !isRecord(body.domainDepths)) {
                writeJson(response, 400, {
                    error: "invalid_request",
                    message: "Expected JSON body with domainDepths object mapping domain names to off/summary/detail.",
                });
                return true;
            }
            const updates = {};
            const rawDepths = body.domainDepths;
            for (const domainId of SEED_DOMAIN_IDS) {
                const raw = rawDepths[domainId];
                if (raw === undefined)
                    continue;
                if (typeof raw === "string" &&
                    SYNC_DEPTHS.includes(raw)) {
                    updates[domainId] = raw;
                }
            }
            // Apply updates in-memory (sync config is runtime-only, not persisted).
            if (app.syncConfig?.domainDepths) {
                Object.assign(app.syncConfig.domainDepths, updates);
            }
            const summary = app.syncConfig?.domainDepths ?? {};
            writeJson(response, 200, { domainDepths: summary }, {
                surface: "sync.options",
                scanOptions: SYNC_OPTIONS_SCAN_OPTIONS,
            });
        }
        catch {
            writeJson(response, 500, {
                error: "sync_options_update_failed",
                message: "Could not update sync options.",
            });
        }
        return true;
    }
    return false;
}
