import type { Essentials } from '@wix/fe-essentials/core';
import { Trans, useExperiments, useTranslation } from '@wix/yoshi-flow-bm';
import {
  WixPatternsEssentials,
  WixPatternsEssentialsOverrides,
  createAccountComponentSettings,
  getWixPatternsWindowExperiments,
  getExperimentsCompat,
  Environment,
} from '@wix/bex-core';

export function buildWixPatternsEssentials(
  essentials: Essentials,
  { overrides }: { overrides?: Partial<WixPatternsEssentialsOverrides> } = {},
): WixPatternsEssentials {
  const {
    errorMonitor,
    httpClient,
    environment: essentialsEnvironment,
    errorHandler,
  } = essentials;

  const environment = {
    ...essentialsEnvironment,
    ...overrides?.environment,
    providerType: 'giza' as const,
  };

  return {
    createEssentials: (options) =>
      essentials.createChildEssentials({
        ...options,
        experiments: {
          bag: getWixPatternsWindowExperiments() ?? {},
        },
      }),
    errorMonitor: errorMonitor ?? { captureException: () => {} },
    errorHandler: errorHandler.v2,
    useTranslation,
    biLogger:
      process.env.NODE_ENV !== 'test'
        ? essentials.asPartial.biLogger
        : undefined,
    Trans,
    useExperiments: () => useExperiments({ readOnly: true }),
    showToast: () => ({ remove: () => {} }),
    httpClient,
    experiments: getExperimentsCompat(essentials),
    createComponentSettings: createAccountComponentSettings,
    ...overrides,
    user: {
      permissions: [],
      ...overrides?.user,
    },
    environment,
    environmentBI: {
      artifactId: essentials.environment.artifactId,
      componentId: (essentials.environment as Environment).componentId,
    },
  };
}
