import { requireAuth } from "../security/http-auth.js";
function normalizeAnswers(value) {
    if (!value || typeof value !== "object")
        return null;
    const out = {};
    for (const [key, rawAnswer] of Object.entries(value)) {
        if (!rawAnswer || typeof rawAnswer !== "object")
            continue;
        const answer = rawAnswer;
        out[key] = {
            selected: Array.isArray(answer.selected)
                ? answer.selected.filter((item) => typeof item === "string")
                : [],
            freeText: typeof answer.freeText === "string" && answer.freeText.trim() ? answer.freeText : null,
            skipped: answer.skipped === true,
        };
    }
    return out;
}
export function registerUserQuestionRoutes(app, config, userQuestions) {
    app.get("/api/user-questions/requests", async (request, reply) => {
        const authUser = await requireAuth(request, reply, config.jwtSecret);
        if (!authUser)
            return;
        const query = request.query;
        return {
            requests: userQuestions.listPending(typeof query.sessionId === "string" ? query.sessionId : undefined, authUser.id),
        };
    });
    app.post("/api/user-questions/requests/:id/submit", async (request, reply) => {
        const authUser = await requireAuth(request, reply, config.jwtSecret);
        if (!authUser)
            return;
        const { id } = request.params;
        const body = (request.body ?? {});
        const answers = normalizeAnswers(body.answers);
        if (!answers)
            return reply.status(400).send({ error: "answers object is required" });
        const ok = userQuestions.submit(id, { answers }, authUser.id);
        if (!ok)
            return reply.status(404).send({ error: "Question request not found" });
        return { ok: true };
    });
    app.post("/api/user-questions/requests/:id/cancel", async (request, reply) => {
        const authUser = await requireAuth(request, reply, config.jwtSecret);
        if (!authUser)
            return;
        const { id } = request.params;
        const ok = userQuestions.cancel(id, authUser.id);
        if (!ok)
            return reply.status(404).send({ error: "Question request not found" });
        return { ok: true };
    });
}
//# sourceMappingURL=user-questions.js.map