/**
 * NextAuth → AuthContext bridge.
 *
 * Routes call requireAuthContext() to obtain a plain { userId, role }
 * object they can pass into MonitorAuthorization / MonitorService. Keeps
 * the policy module free of any NextAuth knowledge.
 */
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/lib/auth';
import { AuthContext, AuthorizationError, Role } from './types';

const VALID_ROLES: ReadonlyArray<Role> = ['ADMIN', 'ADMIN_READ_ONLY', 'EDITOR', 'VIEWER'];

function coerceRole(value: unknown): Role {
    if (typeof value === 'string' && (VALID_ROLES as ReadonlyArray<string>).includes(value)) {
        return value as Role;
    }
    return 'VIEWER';
}

export async function requireAuthContext(): Promise<AuthContext> {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
        // 401 = missing/invalid credentials (no session at all)
        // 403 = authenticated but role check fails (raised by withAuth)
        throw new AuthorizationError('Unauthenticated', 401);
    }
    return {
        userId: parseInt(session.user.id),
        role: coerceRole(session.user.role),
    };
}
