import { mock } from "jest-mock-extended";

import { ForwarderContext } from "../engine";

import { FirefoxRelay, FirefoxRelaySettings } from "./firefox-relay";

describe("Firefox Relay forwarder", () => {
  const context = mock<ForwarderContext<FirefoxRelaySettings>>();

  afterEach(() => {
    jest.resetAllMocks();
  });

  describe("authenticate", () => {
    it("returns a token header", () => {
      context.authenticationToken.mockReturnValue("token");

      const result = FirefoxRelay.authenticate(null, context);

      expect(result).toEqual({ Authorization: "Token token" });
      expect(context.authenticationToken).toHaveBeenCalled();
    });
  });

  describe("settings", () => {
    it("should pass through deserialization", () => {
      const value: any = {};
      const result = FirefoxRelay.forwarder.settings.deserializer(value);
      expect(result).toBe(value);
    });
  });

  describe("importBuffer", () => {
    it("should pass through deserialization", () => {
      const value: any = {};
      const result = FirefoxRelay.forwarder.importBuffer.options.deserializer(value);
      expect(result).toBe(value);
    });
  });

  describe("createForwardingEmail", () => {
    describe("url", () => {
      it("returns the alias path", () => {
        context.baseUrl.mockReturnValue("");

        const result = FirefoxRelay.forwarder.createForwardingEmail.url(null, context);

        expect(result).toEqual("/v1/relayaddresses/");
      });
    });

    describe("body", () => {
      it("returns the alias path", () => {
        context.website.mockReturnValue("website");
        context.generatedBy.mockReturnValue("generated by");

        const result = FirefoxRelay.forwarder.createForwardingEmail.body(null, context);

        expect(context.website).toHaveBeenCalledWith(null, { maxLength: 255 });
        expect(context.generatedBy).toHaveBeenCalledWith(null, {
          extractHostname: true,
          maxLength: 64,
        });
        expect(result).toEqual({
          enabled: true,
          generated_for: "website",
          description: "generated by",
        });
      });
    });

    describe("hasJsonPayload", () => {
      it.each([[200], [201]])("returns true when the status is $%i", (status) => {
        const result = FirefoxRelay.forwarder.createForwardingEmail.hasJsonPayload(
          { status } as Response,
          context,
        );
        expect(result).toBeTruthy();
      });
    });

    describe("processJson", () => {
      it("should read the email from the response", () => {
        const json = { full_address: "foo@example.com" };
        const result = FirefoxRelay.forwarder.createForwardingEmail.processJson(json, context);
        expect(result).toEqual(["foo@example.com"]);
      });
    });
  });
});
