import { InMemoryBackend } from '../testkit/backend';
import { Chance } from 'chance';
import { queryItems } from '@wix/bex-utils/@wix/ambassador-items-selection-spi-host-v1-provider/http';
import { aItem } from '@wix/bex-utils/@wix/ambassador-items-selection-spi-host-v1-provider/builders';
import { Item } from '@wix/bex-utils/@wix/ambassador-items-selection-spi-host-v1-provider/types';

export function createItems(chance: Chance.Chance) {
  return ({ ...overrides }: Partial<Item> = {}) =>
    aItem({
      id: chance.guid(),
      ...overrides,
    });
}

export function createBackend() {
  const chance = new Chance();
  return new InMemoryBackend<Item>({
    total: 10,
    paginationMode: 'offset',
    delay: { min: 100, max: 2000 },
    createOne: () =>
      aItem({
        id: chance.guid(),
        name: chance.name(),
        description: chance.sentence({ words: 5 }),
      }),
    orderBy: (query) => {
      return [...(query.sort ?? [])];
    },
    itemKey: (item) => item.id!,
  });
}

export const itemsSelectionAPIHttpClientMocks = (
  whenRequest: typeof import('@wix/http-client-testkit/client').whenRequest,
) => {
  const itemsSelectionBackend = createBackend();
  return [
    whenRequest(queryItems)
      .reply(200, async () => {
        return itemsSelectionBackend
          .fetchData({
            limit: 10,
          })
          .then(({ items }) => {
            return { items };
          });
      })
      .persist(),
  ];
};
