import { UnauthorizedException } from '@nestjs/common';
import type { Request } from 'express';
import { MeController } from './me.controller';

function makeReq(
  user: {
    oid: string;
    tid: string;
    username: string;
    displayName: string;
    amr: readonly string[];
    roles: readonly string[];
  } | null,
): Request {
  return { session: { user } } as unknown as Request;
}

describe('MeController', () => {
  const controller = new MeController();

  it('returns canAccessAdmin: true when the session carries Portal.Admin', () => {
    const result = controller.capabilities(
      makeReq({
        oid: 'oid-1',
        tid: 'tenant-1',
        username: 'admin@apf.example',
        displayName: 'Admin Smith',
        amr: ['pwd', 'mfa'],
        roles: ['Portal.Admin', 'Other.Role'],
      }),
    );
    expect(result).toEqual({ canAccessAdmin: true });
  });

  it('returns canAccessAdmin: false when the session lacks Portal.Admin', () => {
    const result = controller.capabilities(
      makeReq({
        oid: 'oid-2',
        tid: 'tenant-1',
        username: 'jane.doe@apf.example',
        displayName: 'Jane Doe',
        amr: ['pwd'],
        roles: ['Other.Role'],
      }),
    );
    expect(result).toEqual({ canAccessAdmin: false });
  });

  it('returns canAccessAdmin: false when the session carries no roles', () => {
    const result = controller.capabilities(
      makeReq({
        oid: 'oid-3',
        tid: 'tenant-1',
        username: 'guest@apf.example',
        displayName: 'Guest',
        amr: [],
        roles: [],
      }),
    );
    expect(result).toEqual({ canAccessAdmin: false });
  });

  it('throws Unauthorized when no session is present', () => {
    expect(() => controller.capabilities(makeReq(null))).toThrow(UnauthorizedException);
  });

  it('does NOT echo the raw roles array in the response (curated view contract)', () => {
    const result = controller.capabilities(
      makeReq({
        oid: 'oid-4',
        tid: 'tenant-1',
        username: 'admin@apf.example',
        displayName: 'Admin',
        amr: ['pwd', 'mfa'],
        roles: ['Portal.Admin', 'Confidential.Role'],
      }),
    );
    expect(Object.keys(result)).toEqual(['canAccessAdmin']);
    expect(JSON.stringify(result)).not.toContain('Confidential.Role');
    expect(JSON.stringify(result)).not.toContain('Portal.Admin');
  });
});
