import { whenRequest } from '@wix/fe-essentials/http-client/testkit/client';
import { queryMarketListing } from '@wix/bex-utils/@wix/ambassador-devcenter-app-market-listing-v1-market-listing/http';
import { MarketListing } from '@wix/bex-utils/@wix/ambassador-devcenter-app-market-listing-v1-market-listing/types';
import { InMemoryBackend } from '../testkit/backend';

export function createApp({
  createdDate = new Date(Date.now() - 365 * 24 * 60 * 60 * 1000),
  updatedDate = createdDate,
  ...overrides
}: Partial<MarketListing> = {}): MarketListing {
  return {
    createdDate,
    updatedDate,
    ...overrides,
  };
}

export function createBackend(apps: MarketListing[]) {
  return new InMemoryBackend<MarketListing>({
    total: apps.length,
    paginationMode: 'offset',
    delay: { min: 100, max: 2000 },
    createOne: (index: number) => createApp(apps[index]),
    predicate: (query) => {
      const filters = query.filters ?? {};
      const { appId, languageCode } = filters;
      return (item) =>
        appId.includes(item.appId) && languageCode.includes(item.languageCode);
    },
    orderBy: (query) => {
      return [...(query.sort ?? [])];
    },
    itemKey: (item) => item.id!,
  });
}

export const appsAPIHttpClientMocks = (apps: MarketListing[]) => {
  const appsBackend = createBackend(apps);
  return [
    whenRequest(queryMarketListing)
      .reply(200, async ({ query: { filter } }) => {
        return appsBackend
          .fetchData({
            filters: {
              appId: filter?.appId,
              languageCode: filter?.languageCode,
            },
            limit: 100,
          })
          .then(({ items }) => {
            return { marketListing: items };
          });
      })
      .persist(),
  ];
};
