import { ArgumentsHost, Catch, HttpStatus, type ExceptionFilter } from '@nestjs/common';
import { PolicyDeniedError } from '@insignia/iios-contracts';
import type { Response } from 'express';

/**
 * Maps a fail-closed `PolicyDeniedError` (from `decideOrThrow`) to HTTP 403 instead of a
 * generic 500, so callers can tell "policy denied" (with the reason) from a server fault.
 * Applies to every policy-gated REST endpoint (e.g. the DM-cap / membership rules).
 */
@Catch(PolicyDeniedError)
export class PolicyDeniedFilter implements ExceptionFilter {
  catch(err: PolicyDeniedError, host: ArgumentsHost): void {
    const res = host.switchToHttp().getResponse<Response>();
    res.status(HttpStatus.FORBIDDEN).json({ statusCode: 403, code: err.code, message: err.message });
  }
}
