import { DataExtensionField } from '@wix/bex-core';
import { listDataExtensionSchemas } from '@wix/bex-utils/@wix/ambassador-data-extensions-v1-data-extension-schema/http';
import type { ListDataExtensionSchemasResponse } from '@wix/bex-utils/@wix/ambassador-data-extensions-v1-data-extension-schema/types';
import { Chance } from 'chance';

export function dataExtensionServiceMocks(
  whenRequest: typeof import('@wix/http-client-testkit/client').whenRequest,
) {
  return {
    mocks: [
      whenRequest(listDataExtensionSchemas)
        .reply(200, async () => {
          const res: ListDataExtensionSchemasResponse = {
            dataExtensionSchemas: [],
          };

          return res;
        })
        .persist(),
    ] as import('@wix/http-client-testkit').AnyScenario[],
  };
}

export const aDataExtensionField = (
  overrides: Partial<DataExtensionField> = {},
): DataExtensionField => {
  const chance = new Chance();
  return {
    id: `${chance.word()}_${chance.integer({ min: 0, max: 1000 })}`,
    title: chance.name(),
    type: 'string',
    'x-wix-permissions': {
      read: ['apps', 'users'],
      write: ['apps'],
    },
    'x-wix-created-date': '2023-06-05T11:15:39+00:00',
    ...overrides,
  };
};

export const resolveDataExtensions = ({
  whenRequest,
  fqdn,
  fields,
  extensionPoint,
  persist = true,
}: {
  whenRequest: typeof import('@wix/http-client-testkit/client').whenRequest;
  fqdn: string;
  fields: DataExtensionField[];
  extensionPoint?: string;
  persist?: boolean;
}) => {
  const chance = new Chance();
  const request = whenRequest(listDataExtensionSchemas).reply(200, async () => {
    return {
      dataExtensionSchemas: [
        {
          id: chance.guid(),
          fqdn,
          extensionPoint,
          namespace: '_user_fields',
          jsonSchema: {
            properties: fields.reduce<{ [key: string]: Object }>(
              (acc, curr) => {
                acc[curr.id] = curr;
                return acc;
              },
              {},
            ),
          },
        },
      ],
    };
  });

  if (persist) {
    return request.persist();
  }

  return request;
};
