import * as crypto from 'crypto';
import axios from 'axios';
import { RoadrunnerClient, RoadrunnerError } from './roadrunner.client';

jest.mock('axios');

const sha = (s: string) => crypto.createHash('sha256').update(s).digest('hex');
const hmac = (key: string, s: string) =>
  crypto.createHmac('sha256', key).update(s).digest('hex');

describe('RoadrunnerClient', () => {
  const client = new RoadrunnerClient();
  const cfg = {
    baseUrl: 'https://staging.roadrunnerzw.com/api',
    keyId: 'rr_live_ABC',
    secret: 'rrsk_secret',
  };
  const request = axios.request as jest.Mock;

  beforeEach(() => request.mockReset());

  it('signs requests as documented: key.ts.METHOD.host+path.sha256(body)', async () => {
    request.mockResolvedValue({ status: 202, data: { id: 'dlv_1' } });
    await client.createDelivery(cfg, { a: 1 }, 'ORD-1-abc');

    const call = request.mock.calls[0][0];
    const ts = call.headers['X-RR-Timestamp'];
    const expected = hmac(
      cfg.secret,
      `rr_live_ABC.${ts}.POST.staging.roadrunnerzw.com/api/v1/deliveries.${sha('{"a":1}')}`,
    );
    expect(call.data).toBe('{"a":1}');
    expect(call.headers.Authorization).toBe('Bearer rr_live_ABC');
    expect(call.headers['X-RR-Signature']).toBe(expected);
    expect(call.headers['Idempotency-Key']).toBe('ORD-1-abc');
  });

  it('hashes the empty string for bodiless requests', async () => {
    request.mockResolvedValue({ status: 200, data: { ok: true } });
    await client.ping(cfg);

    const call = request.mock.calls[0][0];
    const ts = call.headers['X-RR-Timestamp'];
    expect(call.data).toBeUndefined();
    expect(call.headers['X-RR-Signature']).toBe(
      hmac(
        cfg.secret,
        `rr_live_ABC.${ts}.GET.staging.roadrunnerzw.com/api/v1/ping.${sha('')}`,
      ),
    );
  });

  it('surfaces the error envelope', async () => {
    request.mockResolvedValue({
      status: 422,
      data: {
        error: {
          type: 'validation_error',
          code: 'address_not_zimbabwean',
          message: 'We only deliver within Zimbabwe.',
          details: [{ field: 'dropoff.address', issue: 'unserviceable' }],
        },
      },
    });
    await expect(client.createQuote(cfg, {})).rejects.toMatchObject({
      status: 422,
      code: 'address_not_zimbabwean',
    });
    await expect(client.createQuote(cfg, {})).rejects.toBeInstanceOf(
      RoadrunnerError,
    );
  });

  describe('verifyWebhook', () => {
    const secret = 'whsec_test';
    const body = '{"type":"delivery.delivered","data":{"id":"dlv_1"}}';
    const now = () => Math.floor(Date.now() / 1000).toString();
    const sign = (ts: string) => hmac(secret, `${ts}.${sha(body)}`);

    it('accepts a valid signature', () => {
      const ts = now();
      expect(client.verifyWebhook(secret, ts, sign(ts), body)).toBe(true);
    });

    it('accepts any of several comma-separated signatures (secret rotation)', () => {
      const ts = now();
      expect(
        client.verifyWebhook(secret, ts, `deadbeef, ${sign(ts)}`, body),
      ).toBe(true);
    });

    it('rejects a wrong signature or a stale timestamp', () => {
      const ts = now();
      expect(
        client.verifyWebhook(
          secret,
          ts,
          sign(ts).replace(/.$/, '0'),
          body + ' ',
        ),
      ).toBe(false);
      const old = (Math.floor(Date.now() / 1000) - 600).toString();
      expect(client.verifyWebhook(secret, old, sign(old), body)).toBe(false);
    });
  });
});
