// app/api/hail/guard.js — shared auth guard for HAIL API routes.
//
// HAIL holds the most sensitive data in the product (a principal's operating
// model). Both reads and writes require an authenticated practitioner
// (admin/owner). This closes the "any caller on the port can read confidential
// interview content" gap in multi-tenant (supabase) mode. Not a route file —
// Next.js only treats `route.js` as an endpoint.

import { requireSession } from '../../../lib/auth.js';

export async function requirePractitioner(req) {
  const session = await requireSession(req);
  if (session.role !== 'admin' && session.role !== 'owner') {
    throw { status: 403, error: 'forbidden' };
  }
  return session;
}

// Map a thrown error (with optional `.status`) to a JSON Response.
export function errorResponse(err, fallbackStatus = 500) {
  if (err && typeof err === 'object' && err.status) {
    return Response.json({ ok: false, error: err.error || err.code || err.message || 'error', message: err.message }, { status: err.status });
  }
  return Response.json({ ok: false, error: err?.message || 'server_error' }, { status: fallbackStatus });
}
