import crypto from 'crypto';
import { afterEach, describe, expect, it, vi } from 'vitest';

const ORIGINAL_ENV = { ...process.env };

describe('validateWebhookSignature', () => {
  afterEach(() => {
    vi.resetModules();
    process.env = { ...ORIGINAL_ENV };
  });

  it('fails closed when the signature key is missing', async () => {
    process.env.AUTHNET_API_LOGIN_ID = 'login-id';
    process.env.AUTHNET_SIGNATURE_KEY = '';

    const { validateWebhookSignature } = await import('../authnet');

    expect(validateWebhookSignature('anything', 'txn-1', '4.99')).toBe(false);
  });

  it('accepts the expected Authorize.Net signature', async () => {
    process.env.AUTHNET_API_LOGIN_ID = 'login-id';
    process.env.AUTHNET_SIGNATURE_KEY = '00112233445566778899AABBCCDDEEFF';

    const { validateWebhookSignature } = await import('../authnet');

    const hashValue = '^login-id^txn-1^4.99^';
    const signature = crypto
      .createHmac('sha512', Buffer.from(process.env.AUTHNET_SIGNATURE_KEY, 'hex'))
      .update(hashValue)
      .digest('hex')
      .toUpperCase();

    expect(validateWebhookSignature(signature, 'txn-1', '4.99')).toBe(true);
    expect(validateWebhookSignature(`${signature.slice(0, -1)}0`, 'txn-1', '4.99')).toBe(false);
  });
});
