import { renderHook } from "@testing-library/react-hooks";
import { encodeParams } from "@applicaster/zapp-pipes-v2-client/src/utils";

const appData = {
  platform: "foo",
  version_name: "1.2.0",
  sdk_version: "2.0.0",
};

const mockUseInflatedUrl = jest.fn();

jest.mock(
  "@applicaster/zapp-react-native-utils/reactHooks/feed/useInflatedUrl",
  () => ({
    useInflatedUrl: mockUseInflatedUrl,
  })
);

const { useBuildPipesUrl } = require("../useBuildPipesUrl");

describe("useBuildPipesUrl", () => {
  it("returns the proper url", async () => {
    mockUseInflatedUrl.mockReturnValue("http://foo.com/show/show-1");
    const url = "http://foo.com/show/{{showId}}";

    const mapping = {
      showId: {
        property: "id",
        source: "entry",
      },
    };

    const buildResult = {
      params: {
        ctx: encodeParams({ platform: appData.platform }),
        version: appData.version_name,
      },
      headers: { SDK: appData.sdk_version },
    };

    const mockedRequestBuilder = {
      build: jest.fn(() => Promise.resolve(buildResult)),
    };

    const { result, waitForNextUpdate } = renderHook(() =>
      useBuildPipesUrl({ url, mapping, requestBuilder: mockedRequestBuilder })
    );

    expect(result.current.url).toBe("http://foo.com/show/show-1");
    expect(result.current.requestParams).toBeNull();

    await waitForNextUpdate();

    expect(result.current.requestParams).toEqual(
      expect.objectContaining({
        params: {
          version: appData.version_name,
          ctx: encodeParams({ platform: appData.platform }),
        },
        headers: {
          SDK: appData.sdk_version,
        },
      })
    );
  });

  it("returns empty object if url is not in endpoints", async () => {
    mockUseInflatedUrl.mockReturnValue("http://foobar.com/show-1");
    const url = "http://foobar.com/{{showId}}";

    const mapping = {
      showId: {
        property: "id",
        source: "entry",
      },
    };

    const buildResult = {};

    const mockedRequestBuilder = {
      build: jest.fn(() => Promise.resolve(buildResult)),
    };

    const { result, waitForNextUpdate } = renderHook(() =>
      useBuildPipesUrl({ url, mapping, requestBuilder: mockedRequestBuilder })
    );

    expect(result.current.url).toBe("http://foobar.com/show-1");
    expect(result.current.requestParams).toBeNull();

    await waitForNextUpdate();

    expect(result.current.requestParams).toEqual({});
  });
});
