// Unit test for the ASSN webhook routing decode (PR #1381 review P1): we read
// bundleId/environment from the UNVERIFIED payload only to select the matching
// PaymentMethod before trusted verification.

import { peekNotificationRouting } from '../../../src/integrations/app-store/notification-routing';

function jwsWithPayload(obj: unknown): string {
  const b64 = (s: string) => Buffer.from(s).toString('base64url');
  return `${b64('{"alg":"ES256"}')}.${b64(JSON.stringify(obj))}.sig`;
}

describe('peekNotificationRouting', () => {
  it('extracts bundleId + environment from the JWS payload (no signature check)', () => {
    const token = jwsWithPayload({ data: { bundleId: 'com.example.app', environment: 'Sandbox' } });
    expect(peekNotificationRouting(token)).toEqual({ bundleId: 'com.example.app', environment: 'Sandbox' });
  });

  it('returns undefined fields when data is absent', () => {
    const token = jwsWithPayload({ notificationType: 'TEST' });
    expect(peekNotificationRouting(token)).toEqual({ bundleId: undefined, environment: undefined });
  });

  it('returns null for a malformed (non-JWS / non-JSON) payload', () => {
    expect(peekNotificationRouting('not-a-jws')).toBeNull();
    expect(peekNotificationRouting('a.@@@.c')).toBeNull();
  });
});
