/**
 * Notification-rule authorization policy.
 *
 * The settings UI already gates the rules editor behind ADMIN /
 * ADMIN_READ_ONLY at the page level (src/app/settings/page.tsx). This
 * module enforces the same policy at the API boundary so that any
 * authenticated user who hand-crafts a request to /api/notification-rules
 * cannot read, create, edit, or delete rules belonging to other users
 * (the IDOR flagged in the May 2026 review).
 *
 *   | Role             | Read | Write | Delete |
 *   | ADMIN            | yes  | yes   | yes    |
 *   | ADMIN_READ_ONLY  | yes  | no    | no     |
 *   | EDITOR           | no   | no    | no     |
 *   | VIEWER           | no   | no    | no     |
 *
 * EA uses notification rules as an operator-only feature; this matches
 * the UI gate exactly. Loosen if non-admin authoring is ever needed.
 */
import { AuthContext, AuthorizationError } from './types';

export const NotificationRuleAuthorization = {
    canRead(ctx: AuthContext): boolean {
        return ctx.role === 'ADMIN' || ctx.role === 'ADMIN_READ_ONLY';
    },

    canWrite(ctx: AuthContext): boolean {
        return ctx.role === 'ADMIN';
    },

    assertCanRead(ctx: AuthContext): void {
        if (!this.canRead(ctx)) {
            throw new AuthorizationError('Only admins may view notification rules');
        }
    },

    assertCanWrite(ctx: AuthContext): void {
        if (!this.canWrite(ctx)) {
            throw new AuthorizationError('Only admins may modify notification rules');
        }
    },
};
