import type { Request, Response } from 'express';
import { omnlSensitiveRouteGuard } from './omnl-guards';

describe('omnlSensitiveRouteGuard', () => {
  const oldKey = process.env.OMNL_API_KEY;

  afterEach(() => {
    if (oldKey === undefined) delete process.env.OMNL_API_KEY;
    else process.env.OMNL_API_KEY = oldKey;
  });

  it('passes when OMNL_API_KEY unset', () => {
    delete process.env.OMNL_API_KEY;
    const next = jest.fn();
    omnlSensitiveRouteGuard({ headers: {}, query: {} } as unknown as Request, {} as Response, next);
    expect(next).toHaveBeenCalled();
  });

  it('401 when key set and no auth', () => {
    process.env.OMNL_API_KEY = 'abc';
    const json = jest.fn();
    const status = jest.fn().mockReturnValue({ json });
    omnlSensitiveRouteGuard({ headers: {}, query: {} } as unknown as Request, { status } as unknown as Response, jest.fn());
    expect(status).toHaveBeenCalledWith(401);
  });

  it('passes with Bearer token', () => {
    process.env.OMNL_API_KEY = 'abc';
    const next = jest.fn();
    omnlSensitiveRouteGuard(
      { headers: { authorization: 'Bearer abc' }, query: {} } as unknown as Request,
      {} as Response,
      next
    );
    expect(next).toHaveBeenCalled();
  });
});
