import * as redux from "react-redux";
import store from "../../store";
import { Router } from "react-router-dom";
import history from "../../store/utils/history";
import { mockState } from "../../mockState";
import { render } from "@testing-library/react";
import AdsPage from "../../pages/AdsPage/AdsPage";
import * as api from "../../request/adsRequest";
import { runSaga } from "redux-saga";
import { FETCH_ADS_REQ } from "../../store/actions/ads/adsActionConstants";
import ColorModeProvider from "../../context/ColorModeContext";
import * as fc from "../../store/saga/adsSaga";
import { setAds, setFilteredAds } from "../../store/actions/ads/adsAction";
import { setArchiveAds } from "../../store/actions/archiveAds/archiveAdsActions";
import { setAd } from "../../store/actions/ad/adActions";

describe("Ads reducer tests", () => {
  const cont = (
    <redux.Provider store={store}>
      <Router history={history}>
        <ColorModeProvider>
          <AdsPage />
        </ColorModeProvider>
      </Router>
    </redux.Provider>
  );

  let spyOnUseSelector;
  let spyOnUseDispatch;
  let mockDispatch;

  beforeEach(() => {
    spyOnUseSelector = jest.spyOn(redux, "useSelector");
    spyOnUseSelector.mockReturnValueOnce(mockState.ads);

    spyOnUseDispatch = jest.spyOn(redux, "useDispatch");

    mockDispatch = jest.fn();
    spyOnUseDispatch.mockReturnValue(mockDispatch);
  });

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

  it("Should dispatch get ads request when rendered", () => {
    render(cont);
    expect(mockDispatch).toHaveBeenCalledWith({
      type: FETCH_ADS_REQ,
    });
  });

  it("Should load and handle ads in case of success", async () => {
    const dispatchedActions = [];

    const mockedCall = { data: mockState.ads.ads };
    api.getAllAds = jest.fn(() => Promise.resolve(mockedCall));

    const fakeStore = {
      getState: () => mockState.ads.ads,
      dispatch: (action) => dispatchedActions.push(action),
    };

    await runSaga(fakeStore, fc.getAds, {}).done;
    expect(api.getAllAds.mock.calls.length).toBe(1);
    expect(dispatchedActions).toContainEqual(setAds(mockedCall.data));
  });

  it("Should load and handle filtered ads in case of success", async () => {
    const dispatchedActions = [];
    const filter = {
      minimumExperience: 0,
      maximumExperience: 0,
      technologies: [1],
      workHour: "FullTime",
      employmentType: "Work",
    };

    const filteredData = mockState.ads.ads.filter(
      (ad) =>
        ad.minimumExperience >= filter.minimumExperience &&
        ad.minimumExperience <= filter.maximumExperience &&
        ad.workHour === filter.workHour &&
        ad.employmentType === filter.employmentType
    );

    const mockedCall = { data: filteredData };
    api.getAllFilteredAds = jest.fn(() => Promise.resolve(mockedCall));

    const fakeStore = {
      getState: () => mockState.ads.ads,
      dispatch: (action) => dispatchedActions.push(action),
    };

    await runSaga(fakeStore, fc.getFilteredAds, filter).done;
    expect(api.getAllFilteredAds.mock.calls.length).toBe(1);
    expect(dispatchedActions).toContainEqual(setFilteredAds(mockedCall.data));
  });

  it("Should load and handle archived ads in case of success", async () => {
    const dispatchedActions = [];
    const date = new Date();

    const filteredData = mockState.ads.ads.filter((ad) => ad.expiredAt < date);

    const mockedCall = { data: filteredData };
    api.getAllArchiveAds = jest.fn(() => Promise.resolve(mockedCall));

    const fakeStore = {
      getState: () => mockState.ads.ads,
      dispatch: (action) => dispatchedActions.push(action),
    };

    await runSaga(fakeStore, fc.getArchiveAds, {}).done;
    expect(api.getAllArchiveAds.mock.calls.length).toBe(1);
    expect(dispatchedActions).toContainEqual(setArchiveAds(mockedCall.data));
  });

  it("Should load and handle ad by id in case of success", async () => {
    const dispatchedActions = [];
    const id = 1;

    const filteredData = mockState.ads.ads.filter((ad) => ad.id === id);

    const mockedCall = { data: filteredData };
    api.getAdDetailsById = jest.fn(() => Promise.resolve(mockedCall));

    const fakeStore = {
      getState: () => mockState.ads.ads,
      dispatch: (action) => dispatchedActions.push(action),
    };

    await runSaga(fakeStore, fc.getAd, { payload: id }).done;
    expect(api.getAdDetailsById.mock.calls.length).toBe(1);
    expect(dispatchedActions).toContainEqual(setAd(mockedCall.data));
  });
});
