// GET   /api/hail/interviews/[id]            — principal-facing transcript (redacted)
// PATCH /api/hail/interviews/[id]            — pause / resume / set cursor / complete
//
// PATCH body: { action: 'pause' | 'resume' | 'cursor' | 'complete', section_cursor? }
// Both require a practitioner.

import {
  getInterview,
  getTranscript,
  pauseInterview,
  resumeInterview,
  setSectionCursor,
  completeInterview,
} 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 });
    return Response.json({ transcript: getTranscript(id) });
  } catch (err) {
    return errorResponse(err);
  }
}

export async function PATCH(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);
    if (!getInterview(id)) return Response.json({ error: 'interview_not_found' }, { status: 404 });
    let interview;
    switch (body?.action) {
      case 'pause': interview = pauseInterview(id); break;
      case 'resume': interview = resumeInterview(id, { section_cursor: body?.section_cursor || null }); break;
      case 'cursor': interview = setSectionCursor(id, body?.section_cursor); break;
      case 'complete': interview = completeInterview(id); break;
      default: return Response.json({ ok: false, error: 'unknown_action' }, { status: 400 });
    }
    return Response.json({ ok: true, interview });
  } catch (err) {
    return errorResponse(err);
  }
}
