// GET  /api/hail/interviews/[id]/responses  — list responses (redacted projection)
// POST /api/hail/interviews/[id]/responses  — record a classified answer
//
// POST returns 422 when `sensitivity` is missing/invalid — classification at
// capture is mandatory. Both reads and writes require a practitioner; the
// returned response is the redacted projection so restricted/refused cleartext
// never leaves the server.

import {
  getInterview,
  listDisplayResponses,
  recordResponse,
  toDisplayResponse,
} from '../../../../../../lib/hail/interview.js';
import { requirePractitioner, errorResponse } from '../../../guard.js';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export async function GET(req, { params }) {
  const { id } = await params;
  try {
    await requirePractitioner(req);
    if (!getInterview(id)) return Response.json({ error: 'interview_not_found' }, { status: 404 });
    const { searchParams } = new URL(req.url);
    const includeNotes = searchParams.get('include_practitioner_notes') !== '0';
    return Response.json({ responses: listDisplayResponses(id, { include_practitioner_notes: includeNotes }) });
  } catch (err) {
    return errorResponse(err);
  }
}

export async function POST(req, { params }) {
  const { id } = await params;
  let body;
  try { body = await req.json(); } catch { return Response.json({ ok: false, error: 'invalid_json' }, { status: 400 }); }
  try {
    await requirePractitioner(req);
    const response = recordResponse({
      interview_id: id,
      section: body?.section,
      question_key: body?.question_key,
      answer: body?.answer ?? null,
      sensitivity: body?.sensitivity,
      confidence: body?.confidence || null,
      evidence: body?.evidence || null,
      is_practitioner_note: body?.is_practitioner_note === true,
    });
    // Redacted projection — never echo restricted/refused cleartext back.
    return Response.json({ ok: true, response: toDisplayResponse(response) }, { status: 201 });
  } catch (err) {
    return errorResponse(err);
  }
}
