import { ForbiddenException } from '@nestjs/common';

import {
  assertCanApproveContractStep,
  canEditContractStep,
} from './freight-permission.util';
import { FREIGHT_PERMS } from '../seed/freight-permissions.registry';

const userWith = (...keys: string[]) => ({
  permissions: keys.map((key) => ({ key })),
});

describe('hazardous contract approval steps', () => {
  it('rejects an approver who only holds ordinary contract-approve permissions', () => {
    // The blanket "any contract approve permission" fallback must NOT reach
    // dangerous goods — that is the whole point of the dedicated desks.
    const lineStaff = userWith(FREIGHT_PERMS.contracts.approveLineStaff);

    expect(() =>
      assertCanApproveContractStep(lineStaff, 'HAZARDOUS_APPROVAL_ONE'),
    ).toThrow(ForbiddenException);
    expect(canEditContractStep(lineStaff, 'HAZARDOUS_APPROVAL_ONE')).toBe(false);
  });

  it('accepts only the matching hazardous permission', () => {
    const first = userWith(FREIGHT_PERMS.contracts.hazardousApprovalOne);

    expect(() =>
      assertCanApproveContractStep(first, 'HAZARDOUS_APPROVAL_ONE'),
    ).not.toThrow();
    // Holding step one does not confer step two.
    expect(() =>
      assertCanApproveContractStep(first, 'HAZARDOUS_APPROVAL_TWO'),
    ).toThrow(ForbiddenException);
  });

  it('does not let a hazardous approver stand in for the commercial chain', () => {
    const hazardOnly = userWith(
      FREIGHT_PERMS.contracts.hazardousApprovalOne,
      FREIGHT_PERMS.contracts.hazardousApprovalTwo,
    );

    expect(() => assertCanApproveContractStep(hazardOnly, 'CEO')).toThrow(
      ForbiddenException,
    );
  });
});
