import * as React from "react";
import { render } from "@testing-library/react-native";
import { Text } from "react-native";

const mockedUseBuildPipesUrl = jest.fn();

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

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

// eslint-disable-next-line react/display-name
const Wrapped = React.forwardRef((props: any, _ref) => (
  <Text testID="wrapped">{`${props.uri}|${JSON.stringify(props.headers)}`}</Text>
));

describe("withPipesEndpoint", () => {
  afterEach(() => jest.clearAllMocks());

  it("renders nothing while the endpoint context is resolving", () => {
    mockedUseBuildPipesUrl.mockReturnValue({ requestParams: null });

    const Decorated = withPipesEndpoint(Wrapped);
    const { queryByTestId } = render(<Decorated uri="https://foo.com" />);

    expect(queryByTestId("wrapped")).toBeNull();
  });

  it("passes the uri through unchanged when there are no params", () => {
    mockedUseBuildPipesUrl.mockReturnValue({ requestParams: {} });

    const Decorated = withPipesEndpoint(Wrapped);
    const { getByTestId } = render(<Decorated uri="https://foo.com/path" />);

    expect(getByTestId("wrapped").props.children).toBe(
      "https://foo.com/path|{}"
    );
  });

  it("merges resolved params into the uri and forwards headers", () => {
    mockedUseBuildPipesUrl.mockReturnValue({
      requestParams: {
        params: { token: "abc" },
        headers: { Authorization: "Bearer xyz" },
      },
    });

    const Decorated = withPipesEndpoint(Wrapped);
    const { getByTestId } = render(<Decorated uri="https://foo.com/path" />);

    expect(getByTestId("wrapped").props.children).toBe(
      'https://foo.com/path?token=abc|{"Authorization":"Bearer xyz"}'
    );
  });
});
