// app/hail/hail-guard.js — server-component / server-action auth guard for HAIL.
//
// HAIL holds the most sensitive data in the product (a principal's operating
// model). Every /hail page render AND every `'use server'` action must require a
// practitioner (admin/owner) — mirroring app/api/hail/guard.js for the API
// routes. Without this, in supabase (multi-tenant) mode any authenticated
// member/viewer could read or mutate a principal's engagement.
//
// Pattern matches app/admin/page.js: requireSession(null) works in local mode
// (synthetic owner) and resolves the Supabase session otherwise; redirect() is
// called OUTSIDE the try/catch so its NEXT_REDIRECT control-flow isn't swallowed.

import { redirect } from 'next/navigation';
import { requireSession } from '../../lib/auth.js';
import { requireRole } from '../../lib/authz.js';

export async function requirePractitionerPage() {
  let session = null;
  try {
    session = await requireSession(null);
    requireRole(session, 'admin'); // 'admin' minimum → admin or owner; rejects member/viewer
  } catch {
    session = null;
  }
  if (!session) redirect('/login');
  return session;
}
