import { GEOCODER, getCountryBounds } from "../domain/geocoding";

jest.mock("iso-3166-1");

import iso from "iso-3166-1";

describe("geocoding", () => {
  describe("getCountryBounds", () => {
    it("gets bounds for a given country", async () => {
      iso.whereAlpha2.mockReturnValue({ country: "test-country" });
      GEOCODER.geocode.mockReturnValue({
        results: [
          {
            geometry: { viewport: "viewport" },
            types: ["country"],
          },
        ],
      });
      expect(await getCountryBounds("success-test")).toBe("viewport");
      expect(GEOCODER.geocode).toHaveBeenCalledWith(
        expect.objectContaining({
          address: "test-country",
        })
      );
    });
    it("handles missing data gracefully", async () => {
      iso.whereAlpha2.mockReturnValue({ country: "test-country" });
      GEOCODER.geocode.mockReturnValue({
        results: [
          {
            geometry: { viewport: "viewport" },
            types: ["not-country"],
          },
        ],
      });
      expect(await getCountryBounds("bad-data-test")).toBe(null);
    });
    it("suppresses errors and returns null", async () => {
      iso.whereAlpha2.mockReturnValue({ country: "test-country" });
      GEOCODER.geocode.mockImplementation(() => {
        throw new Error();
      });
      expect(await getCountryBounds("error-test")).toBe(null);
    });
    it("uses cache when possible", async () => {
      iso.whereAlpha2.mockReturnValue({ country: "test-country" });
      GEOCODER.geocode.mockReturnValue({
        results: [
          {
            geometry: { viewport: "viewport" },
            types: ["country"],
          },
        ],
      });
      expect(await getCountryBounds("cache-test")).toBe("viewport");
      expect(await getCountryBounds("cache-test")).toBe("viewport");
      expect(GEOCODER.geocode).toHaveBeenCalledTimes(1);
    });
  });
});
