import { logEvent } from '../../security/audit.js';
import { getCaptchaConfig } from '../../security/captcha.js';
import { listForms as listFormsService, getFormById as getFormByIdService, getFormBySlug as getFormBySlugService, createForm as createFormService, updateForm as updateFormService, duplicateForm as duplicateFormService, deleteForm as deleteFormService, saveFormSchema as saveFormSchemaService, getFormSchema as getFormSchemaService, getNotificationSettings as getFormNotificationSettingsService, updateNotificationSettings as updateFormNotificationSettingsService, setNotifyEnabled as setFormNotifyEnabledService, getEmbedSettings as getFormEmbedSettingsService, updateEmbedSettings as updateFormEmbedSettingsService, getFormStats as getFormStatsService, getFormsSidebarCounts as getFormsSidebarCountsService, } from '../../forms/service.js';
import { listEntries as listEntriesService, getEntryWithSchema as getEntryWithSchemaService, getEntryCounts as getEntryCountsService, updateEntry as updateEntryService, bulkUpdateEntries as bulkUpdateEntriesService, deleteEntry as deleteEntryService, exportFormEntries as exportFormEntriesService, } from '../../forms/entries.js';
import { buildPublicForm } from '../../forms/submission.js';
import { resolveSubmissionFields } from '../../forms/submission.js';
import { createFormWebhook, listFormWebhooks, updateFormWebhook, deleteFormWebhook, testFormWebhook, } from '../../forms/webhooks.js';
import { sendFormNotifications } from '../../forms/notify.js';
import { getClientIp } from '../../security/client-ip.js';
import { guardedDb } from '../guarded-db.js';
import { json, errorResponse, internalError, clampPageSize, normalizeSubmission, mapFormError, parseFormsQuery, parseEntriesQuery, formCorsHeaders, jsonWithHeaders, submitToForm, requireAuth, buildActionContext, WRITE_ROLES, requireRole, } from '../route-helpers.js';
export function registerFormRoutes(router) {
    const db = guardedDb;
    // ---------------------------------------------------------------------------
    // Forms routes
    // ---------------------------------------------------------------------------
    router.get('/forms', async (request) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const url = new URL(request.url);
            const { forms, total, page, pageSize } = await listFormsService(parseFormsQuery(url));
            // Response is a superset of the typed FormDefinition with legacy aliases
            // (`submissions`, `fieldCount`) so older admin views keep working while
            // PR3 migrates them to the typed shape.
            const data = forms.map((f) => ({
                ...f,
                fieldCount: f.fields?.length ?? 0,
                submissions: f.totalEntries ?? 0,
            }));
            return json({ data, total, page, pageSize });
        }
        catch (err) {
            return internalError(err);
        }
    });
    router.get('/forms/:id/submissions', async (request, params) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const url = new URL(request.url);
            const page = Number(url.searchParams.get('page')) || 1;
            const pageSize = clampPageSize(url.searchParams.get('pageSize'));
            const skip = (page - 1) * pageSize;
            const [submissions, total] = await Promise.all([
                db().formSubmission.findMany({
                    where: { formId: params.id },
                    skip,
                    take: pageSize,
                    orderBy: { createdAt: 'desc' },
                }),
                db().formSubmission.count({ where: { formId: params.id } }),
            ]);
            return json({
                data: {
                    submissions: submissions.map(normalizeSubmission),
                    total,
                    page,
                    pageSize,
                    totalPages: Math.ceil(total / pageSize),
                },
            });
        }
        catch (err) {
            return internalError(err);
        }
    });
    // Public, unauthenticated form schema — what an embedded form needs to render.
    // CSRF-exempt and CORS-enabled (see handler-factory + formCorsHeaders).
    router.options('/public/forms/:slug', async (request, params) => {
        const form = await getFormBySlugService(params.slug).catch(() => null);
        return new Response(null, {
            status: 204,
            headers: formCorsHeaders(request, form?.embedSettings?.allowedDomains),
        });
    });
    router.get('/public/forms/:slug', async (request, params) => {
        try {
            const form = await getFormBySlugService(params.slug);
            if (!form || form.status !== 'active') {
                return jsonWithHeaders({ error: 'Form not found' }, 404, formCorsHeaders(request));
            }
            const cors = formCorsHeaders(request, form.embedSettings?.allowedDomains);
            const { fields, versionId } = await resolveSubmissionFields(form);
            const captcha = getCaptchaConfig();
            const publicForm = buildPublicForm(form, fields, versionId, {
                captcha: { provider: captcha.provider, siteKey: captcha.siteKey },
            });
            return jsonWithHeaders({ data: publicForm }, 200, cors);
        }
        catch (err) {
            return internalError(err);
        }
    });
    router.options('/public/forms/:slug/submit', async (request, params) => {
        const form = await getFormBySlugService(params.slug).catch(() => null);
        return new Response(null, {
            status: 204,
            headers: formCorsHeaders(request, form?.embedSettings?.allowedDomains),
        });
    });
    router.post('/public/forms/:slug/submit', async (request, params) => {
        try {
            const form = await getFormBySlugService(params.slug);
            if (!form || form.status !== 'active') {
                return jsonWithHeaders({ error: 'Form not found' }, 404, formCorsHeaders(request));
            }
            return submitToForm(request, form);
        }
        catch (err) {
            return internalError(err);
        }
    });
    // Legacy by-id submission endpoint — same pipeline, kept for existing embeds.
    router.post('/forms/:id/submit', async (request, params) => {
        try {
            const form = await getFormByIdService(params.id);
            if (!form || form.status !== 'active') {
                return jsonWithHeaders({ error: 'Form not found' }, 404, formCorsHeaders(request));
            }
            return submitToForm(request, form);
        }
        catch (err) {
            return internalError(err);
        }
    });
    // ---------------------------------------------------------------------------
    // Forms management routes (admin) — services in ../forms/*.
    //
    // Route order matters: the router matches the first registered pattern, and
    // `:id` is a greedy `[^/]+`. All static `/forms/<word>` GETs are registered
    // before `/forms/:id` so e.g. `/forms/entries` is not captured as an id.
    // ---------------------------------------------------------------------------
    router.get('/forms/stats', async (request) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            return json({ data: await getFormStatsService() });
        }
        catch (err) {
            return internalError(err);
        }
    });
    router.get('/forms/sidebar-counts', async (request) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            return json({ data: await getFormsSidebarCountsService() });
        }
        catch (err) {
            return internalError(err);
        }
    });
    router.get('/forms/entries/counts', async (request) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const counts = await getEntryCountsService(parseEntriesQuery(new URL(request.url)));
            return json({ data: counts });
        }
        catch (err) {
            return internalError(err);
        }
    });
    // Defined before `/forms/entries/:entryId` so "export" is not parsed as an id.
    router.get('/forms/entries/export', async (request) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const formId = new URL(request.url).searchParams.get('formId');
            if (!formId)
                return errorResponse('"formId" query parameter is required', 400);
            const result = await exportFormEntriesService(formId);
            if (!result)
                return errorResponse('Form not found', 404);
            // PII access audit: a bulk export of decrypted submission data.
            void logEvent({
                event: 'form.entries.exported',
                userId: auth.session.userId,
                ipAddress: getClientIp(request),
                details: { formId, count: result.count },
            });
            const filename = `${result.formSlug || 'form'}-entries.csv`;
            return new Response(result.csv, {
                status: 200,
                headers: {
                    'Content-Type': 'text/csv; charset=utf-8',
                    'Content-Disposition': `attachment; filename="${filename}"`,
                },
            });
        }
        catch (err) {
            return internalError(err);
        }
    });
    router.get('/forms/entries/:entryId', async (request, params) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const result = await getEntryWithSchemaService(params.entryId);
            if (!result)
                return errorResponse('Entry not found', 404);
            // PII access audit: viewing a single entry exposes its decrypted fields.
            void logEvent({
                event: 'form.entry.viewed',
                userId: auth.session.userId,
                ipAddress: getClientIp(request),
                details: { entryId: params.entryId, formId: result.entry.formId },
            });
            return json({ data: result });
        }
        catch (err) {
            return internalError(err);
        }
    });
    router.patch('/forms/entries/:entryId', async (request, params) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const body = (await request.json().catch(() => ({})));
            const ctx = buildActionContext(auth.session, db());
            const updated = await updateEntryService(ctx, params.entryId, body);
            if (!updated)
                return errorResponse('Entry not found', 404);
            return json({ data: updated });
        }
        catch (err) {
            return internalError(err);
        }
    });
    router.delete('/forms/entries/:entryId', async (request, params) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const ctx = buildActionContext(auth.session, db());
            await deleteEntryService(ctx, params.entryId);
            return json({ data: { success: true } });
        }
        catch (err) {
            return internalError(err);
        }
    });
    router.post('/forms/entries/bulk', async (request) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const body = (await request.json().catch(() => ({})));
            if (!Array.isArray(body.ids) || body.ids.length === 0) {
                return errorResponse('"ids" must be a non-empty array', 400);
            }
            const ctx = buildActionContext(auth.session, db());
            const count = await bulkUpdateEntriesService(ctx, body.ids, body.patch ?? {});
            return json({ data: { updated: count } });
        }
        catch (err) {
            return internalError(err);
        }
    });
    router.get('/forms/entries', async (request) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const result = await listEntriesService(parseEntriesQuery(new URL(request.url)));
            return json({ data: result });
        }
        catch (err) {
            return internalError(err);
        }
    });
    router.post('/forms', async (request) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const body = (await request.json().catch(() => null));
            if (!body || typeof body.name !== 'string' || !body.name.trim()) {
                return errorResponse('"name" is required', 400);
            }
            const ctx = buildActionContext(auth.session, db());
            const form = await createFormService(ctx, body);
            return json({ data: form }, 201);
        }
        catch (err) {
            return mapFormError(err) ?? internalError(err);
        }
    });
    router.get('/forms/:id', async (request, params) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const form = await getFormByIdService(params.id);
            if (!form)
                return errorResponse('Form not found', 404);
            return json({ data: form });
        }
        catch (err) {
            return internalError(err);
        }
    });
    router.patch('/forms/:id', async (request, params) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const body = (await request.json().catch(() => ({})));
            const ctx = buildActionContext(auth.session, db());
            const form = await updateFormService(ctx, params.id, body);
            return json({ data: form });
        }
        catch (err) {
            return mapFormError(err) ?? internalError(err);
        }
    });
    router.delete('/forms/:id', async (request, params) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const url = new URL(request.url);
            const force = url.searchParams.get('force') === 'true';
            const ctx = buildActionContext(auth.session, db());
            await deleteFormService(ctx, params.id, { force });
            return json({ data: { success: true } });
        }
        catch (err) {
            return mapFormError(err) ?? internalError(err);
        }
    });
    router.post('/forms/:id/duplicate', async (request, params) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const ctx = buildActionContext(auth.session, db());
            const form = await duplicateFormService(ctx, params.id);
            return json({ data: form }, 201);
        }
        catch (err) {
            return mapFormError(err) ?? internalError(err);
        }
    });
    router.get('/forms/:id/schema', async (request, params) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const schema = await getFormSchemaService(params.id);
            return json({ data: schema });
        }
        catch (err) {
            return mapFormError(err) ?? internalError(err);
        }
    });
    router.put('/forms/:id/schema', async (request, params) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const body = (await request.json().catch(() => ({})));
            if (!Array.isArray(body.fields)) {
                return errorResponse('"fields" must be an array', 400);
            }
            const ctx = buildActionContext(auth.session, db());
            const result = await saveFormSchemaService(ctx, params.id, body.fields, body.notes);
            return json({ data: result });
        }
        catch (err) {
            return mapFormError(err) ?? internalError(err);
        }
    });
    router.get('/forms/:id/notifications', async (request, params) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const settings = await getFormNotificationSettingsService(params.id);
            return json({ data: settings });
        }
        catch (err) {
            return mapFormError(err) ?? internalError(err);
        }
    });
    router.put('/forms/:id/notifications', async (request, params) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const body = (await request.json().catch(() => ({})));
            const ctx = buildActionContext(auth.session, db());
            const settings = await updateFormNotificationSettingsService(ctx, params.id, body);
            return json({ data: settings });
        }
        catch (err) {
            return mapFormError(err) ?? internalError(err);
        }
    });
    // Lightweight notify toggle used by the forms table switch.
    router.put('/forms/:id/notify', async (request, params) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const body = (await request.json().catch(() => ({})));
            const ctx = buildActionContext(auth.session, db());
            const settings = await setFormNotifyEnabledService(ctx, params.id, Boolean(body.enabled));
            return json({ data: { notifyEnabled: settings.enabled } });
        }
        catch (err) {
            return mapFormError(err) ?? internalError(err);
        }
    });
    router.get('/forms/:id/embed', async (request, params) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const settings = await getFormEmbedSettingsService(params.id);
            return json({ data: settings });
        }
        catch (err) {
            return mapFormError(err) ?? internalError(err);
        }
    });
    router.put('/forms/:id/embed', async (request, params) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const body = (await request.json().catch(() => ({})));
            const ctx = buildActionContext(auth.session, db());
            const settings = await updateFormEmbedSettingsService(ctx, params.id, body);
            return json({ data: settings });
        }
        catch (err) {
            return mapFormError(err) ?? internalError(err);
        }
    });
    // ── Per-form webhooks (CRUD + test) ──────────────────────────────────────
    router.get('/forms/:id/webhooks', async (request, params) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const form = await getFormByIdService(params.id);
            if (!form)
                return errorResponse('Form not found', 404);
            const webhooks = await listFormWebhooks(params.id);
            return json({ data: webhooks });
        }
        catch (err) {
            return mapFormError(err) ?? internalError(err);
        }
    });
    router.post('/forms/:id/webhooks', async (request, params) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const form = await getFormByIdService(params.id);
            if (!form)
                return errorResponse('Form not found', 404);
            const body = (await request.json().catch(() => ({})));
            if (!body.url || typeof body.url !== 'string') {
                return errorResponse('A webhook url is required', 400);
            }
            const ctx = buildActionContext(auth.session, db());
            const webhook = await createFormWebhook(ctx, params.id, body);
            // The plaintext secret is returned exactly once here, on creation.
            return json({ data: webhook }, 201);
        }
        catch (err) {
            return mapFormError(err) ?? internalError(err);
        }
    });
    router.patch('/forms/:id/webhooks/:webhookId', async (request, params) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const body = (await request.json().catch(() => ({})));
            const ctx = buildActionContext(auth.session, db());
            const webhook = await updateFormWebhook(ctx, params.webhookId, body);
            return json({ data: webhook });
        }
        catch (err) {
            return mapFormError(err) ?? internalError(err);
        }
    });
    router.delete('/forms/:id/webhooks/:webhookId', async (request, params) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const ctx = buildActionContext(auth.session, db());
            await deleteFormWebhook(ctx, params.webhookId);
            return json({ data: { success: true } });
        }
        catch (err) {
            return mapFormError(err) ?? internalError(err);
        }
    });
    router.post('/forms/:id/webhooks/:webhookId/test', async (request, params) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const ctx = buildActionContext(auth.session, db());
            const result = await testFormWebhook(ctx, params.webhookId);
            return json({ data: result });
        }
        catch (err) {
            return mapFormError(err) ?? internalError(err);
        }
    });
    // ── Test notification email ──────────────────────────────────────────────
    router.post('/forms/:id/notifications/test', async (request, params) => {
        try {
            const auth = await requireAuth(request);
            if (auth.error)
                return auth.error;
            const roleErr = requireRole(auth.session.role, WRITE_ROLES);
            if (roleErr)
                return roleErr;
            const form = await getFormByIdService(params.id);
            if (!form)
                return errorResponse('Form not found', 404);
            const settings = await getFormNotificationSettingsService(params.id);
            const primaryRecipient = (settings?.recipients ?? [])[0];
            if (!settings?.enabled || !primaryRecipient) {
                return errorResponse('Configure at least one recipient before sending a test', 400);
            }
            // Sample values so operators see a realistic email. The autoresponder is
            // suppressed for tests so we never email an arbitrary sample address.
            const fields = form.fields ?? [];
            const sampleData = {};
            for (const field of fields) {
                if (field.type === 'honeypot' || field.type === 'divider' || field.type === 'richtext') {
                    continue;
                }
                if (field.type === 'email')
                    sampleData[field.key] = primaryRecipient;
                else if (field.type === 'checkbox' || field.type === 'consent')
                    sampleData[field.key] = true;
                else
                    sampleData[field.key] = `Sample ${field.label || field.key}`;
            }
            const ctx = {
                formId: form.id,
                formName: form.name,
                entryNumber: null,
                submittedAt: new Date().toISOString(),
                fields,
                data: sampleData,
                senderName: 'Test Submission',
                senderEmail: primaryRecipient,
            };
            const result = await sendFormNotifications({ ...settings, autoresponderEnabled: false }, ctx);
            return json({ data: result });
        }
        catch (err) {
            return mapFormError(err) ?? internalError(err);
        }
    });
}
//# sourceMappingURL=forms.js.map