import { EssentialsOptions } from '@wix/fe-essentials/core';
import { ReadOnlyExperiments } from '@wix/fe-essentials/experiments';
import { FlowBusinessManagerModule } from '@wix/yoshi-flow-bm';
import type { ModuleId } from '@wix/business-manager-api';
import { getModule } from '@wix/business-manager-api';

export const buildCreateEssentials = (
  _essentials: FlowBusinessManagerModule['_essentials'],
) => {
  return (
    options: EssentialsOptions & {
      componentSettings?: { componentId?: string };
    },
  ) => {
    return {
      _i18n: options.i18n ? _essentials.createI18n(options.i18n) : null,
      get i18n() {
        return this._i18n!;
      },
      _dataCapsule: options.dataCapsule
        ? _essentials.createDataCapsule(options.dataCapsule)
        : null,
      get dataCapsule() {
        return this._dataCapsule!;
      },
      biLoggerFactory: _essentials.biLoggerFactory,
      _errorMonitor: options.errorMonitor
        ? _essentials.createErrorMonitor(options.errorMonitor)
        : null,
      get errorMonitor() {
        return this._errorMonitor!;
      },
      _fedopsLogger: options.fedops
        ? _essentials.createFedopsLogger(options.fedops.appName)
        : null,
      get fedopsLogger() {
        return this._fedopsLogger!;
      },
      _experiments: (() => {
        if (!options.experiments) {
          return null;
        }

        if ('scopes' in options.experiments) {
          if (getModule('FEDATA' as ModuleId) != null) {
            return _essentials.createExperiments(options.experiments);
          }

          return null;
        }

        const Experiments = _essentials.experiments
          .constructor as typeof ReadOnlyExperiments;

        return new Experiments({
          experiments: options.experiments.bag,
        });
      })(),
      get experiments() {
        return this._experiments!;
      },
    };
  };
};
