import 'server-only'

import { NextResponse } from 'next/server'
import { type SessionUser } from '@/lib/auth'
import { requireSurfaceApi } from '@/lib/auth/surface-guard'

/**
 * Pilot Invitation Manager routes are for HeavyHaul Agent staff only (§8).
 * Gated on the INTERNAL flag (answer 8: "the moderator, not only the admin"
 * — today admin is the only internal role; a Moderator role inherits access
 * the day it is added to INTERNAL_ROLES).
 */
export async function requireInternal(): Promise<{ ok: true; user: SessionUser; actor: { id: string; label: string } } | { ok: false; response: NextResponse }> {
  // Per-page access (2026-09-23): the platform admin, or someone the admin
  // granted the Pilot Invitation Manager. isInternalUser alone is no longer
  // the rule — a moderator is not internal staff.
  const guard = await requireSurfaceApi('pilot_invitations')
  if (!guard.ok) return guard
  return { ok: true, user: guard.user, actor: { id: guard.user.id, label: guard.actor.label } }
}

export function migrationMissing(): NextResponse {
  return NextResponse.json({ error: 'Pilot network tables are missing — apply migration 0018 first.' }, { status: 503 })
}
