import Logger from 'src/application/logging/logger';
import { atom } from 'jotai';
import { EnviveConfig } from 'src/contexts/types';
import { ContextSourceEnum } from '@spiffy-ai/commerce-api-client';
import { LocalStorageKeys } from 'src/contexts/localStorageContext';

const logger = new Logger('enviveConfig');

const internalEnviveConfigAtom = atom<EnviveConfig | undefined>(undefined);

export const enviveConfigAtom = atom(
  get => {
    const config = get(internalEnviveConfigAtom);
    logger.logDebug('enviveConfig.ts: Accessing internalEnviveConfigAtom', config);
    return config; // Return undefined if not set instead of throwing
  },
  (_, set, value: EnviveConfig) => {
    set(internalEnviveConfigAtom, value);
  },
);

export const amplitudeApiKeyAtom = atom(get => {
  const config = get(enviveConfigAtom);
  return config?.amplitudeApiKey;
});
export const dataResidencyAtom = atom(get => {
  const config = get(enviveConfigAtom);
  return config?.dataResidency;
});
export const envAtom = atom(get => {
  const config = get(enviveConfigAtom);
  return config?.env;
});
export const baseUrlAtom = atom(get => {
  const config = get(enviveConfigAtom);
  return config?.baseUrl || 'https://commerce-api.dev.spiffy.ai';
});
export const reactAppNameAtom = atom(get => {
  const config = get(enviveConfigAtom);
  return config?.reactAppName;
});
export const cdnUrlAtom = atom(get => {
  const config = get(enviveConfigAtom);
  return config?.cdnUrl;
});

export const orgIdAtom = atom(get => {
  const config = get(enviveConfigAtom);
  return config?.orgId;
});

export const contextSourceAtom = atom(get => {
  const config = get(enviveConfigAtom);

  if (config?.contextSource) {
    return config.contextSource as ContextSourceEnum;
  }

  const spiffyOnFeatureFlagSet = window.localStorage.getItem(LocalStorageKeys.SpiffyOnOverride);
  if (spiffyOnFeatureFlagSet === 'true') {
    return ContextSourceEnum.Playground;
  }

  return ContextSourceEnum.App;
});

export const orgLevelApiKeyAtom = atom(get => {
  const config = get(enviveConfigAtom);
  logger.logDebug('enviveConfig.ts: Accessing orgLevelApiKey', config);
  return config?.orgLevelApiKey;
});
export const orgShortNameAtom = atom(get => {
  const config = get(enviveConfigAtom);
  logger.logDebug('enviveConfig.ts: Accessing orgShortName', config);
  return config?.orgShortName;
});
