import { decodeJwtPayload, extractPortalClaimState } from '@/lib/auth/claims';

function makeToken(payload: Record<string, unknown>) {
  const encoded = Buffer.from(JSON.stringify(payload)).toString('base64url');
  return `header.${encoded}.signature`;
}

describe('portal auth claims', () => {
  it('decodes JWT payloads safely', () => {
    const payload = decodeJwtPayload(makeToken({ tenantId: 'tenant-123' }));
    expect(payload.tenantId).toBe('tenant-123');
  });

  it('extracts client, tenant, subscription, and roles from mixed claim shapes', () => {
    const state = extractPortalClaimState(
      {
        client_id: 'client-001',
        tenantId: 'tenant-001',
        subscription_id: 'sub-001',
        realm_access: { roles: ['tenant-admin'] },
      },
      {
        roles: ['billing-admin'],
        role: 'operator',
      }
    );

    expect(state.clientId).toBe('client-001');
    expect(state.tenantId).toBe('tenant-001');
    expect(state.subscriptionId).toBe('sub-001');
    expect(state.roles).toEqual(expect.arrayContaining(['tenant-admin', 'billing-admin', 'operator']));
  });
});
