// Confirms Apple's real signature verification is wired up correctly —
// synthetic JWSes are rejected when APP_STORE_SKIP_SIGNATURE_VERIFY is NOT set.
//
// This file deliberately runs WITHOUT the skip env, so it must be the only
// real-mode test file. Other app-store spec files set the skip env at module
// top to be able to exercise control-flow with synthetic fixtures.

/* eslint-disable import/first */
// Ensure the env is *not* set, even if another test file in the same Jest
// worker happened to set it. We delete + reset module caches so a fresh
// verifier is constructed with the correct flag.
delete process.env.APP_STORE_SKIP_SIGNATURE_VERIFY;

import {
  verifySignedNotification,
  verifySignedTransaction,
} from '../../../src/integrations/app-store/signed-data-verifier';

const makeSyntheticJws = (payload: object): string => {
  const header = Buffer.from(JSON.stringify({ alg: 'ES256', x5c: ['fake-cert'] })).toString('base64url');
  const body = Buffer.from(JSON.stringify(payload)).toString('base64url');
  return `${header}.${body}.fake-signature`;
};

describe('signed-data-verifier — real verification path', () => {
  it('rejects synthetic transaction JWS (no valid x5c chain)', async () => {
    const jws = makeSyntheticJws({
      transactionId: 'txn_1',
      originalTransactionId: 'orig_1',
      productId: 'sub_06',
      bundleId: 'com.example.app',
    });
    await expect(verifySignedTransaction(jws, 'com.example.app', 'sandbox')).rejects.toThrow();
  });

  it('rejects synthetic notification JWS (no valid x5c chain)', async () => {
    const jws = makeSyntheticJws({
      notificationType: 'DID_RENEW',
      notificationUUID: 'uuid-1',
      data: { bundleId: 'com.example.app', environment: 'Sandbox' },
    });
    await expect(verifySignedNotification(jws, 'com.example.app', 'sandbox')).rejects.toThrow();
  });

  it('throws when JWS format is structurally invalid', async () => {
    await expect(verifySignedTransaction('not.a.jws', 'com.example.app', 'sandbox')).rejects.toThrow();
  });
});

describe('signed-data-verifier — skip mode', () => {
  beforeAll(() => {
    process.env.APP_STORE_SKIP_SIGNATURE_VERIFY = 'true';
  });
  afterAll(() => {
    delete process.env.APP_STORE_SKIP_SIGNATURE_VERIFY;
  });

  it('decodes synthetic transaction JWS when skip is enabled', async () => {
    const jws = makeSyntheticJws({
      transactionId: 'txn_skip',
      originalTransactionId: 'orig_skip',
      productId: 'sub_06',
      bundleId: 'com.example.app',
    });
    const decoded = await verifySignedTransaction(jws, 'com.example.app', 'sandbox');
    expect(decoded.transactionId).toBe('txn_skip');
  });

  it('refuses malformed JWS even in skip mode (format check still runs)', async () => {
    await expect(verifySignedTransaction('not.a.jws', 'com.example.app', 'sandbox')).rejects.toThrow();
  });
});
