export const DEV_API_SWITCH_STORAGE_KEY = '__chatapp3_admin_dev_api_target__';

export const DEV_API_TARGETS = {
  internal: 'internal',
  prod: 'prod',
} as const;

export type DevApiTarget =
  (typeof DEV_API_TARGETS)[keyof typeof DEV_API_TARGETS];

export const DEV_API_OPTIONS: Array<{
  label: string;
  value: DevApiTarget;
}> = [
  {
    label: '内网 API',
    value: DEV_API_TARGETS.internal,
  },
  {
    label: '线上 API',
    value: DEV_API_TARGETS.prod,
  },
];

const DEV_API_PREFIX_MAP: Record<DevApiTarget, string> = {
  [DEV_API_TARGETS.internal]: '/__dev_api_internal__',
  [DEV_API_TARGETS.prod]: '/__dev_api_prod__',
};

function canUseStorage() {
  return typeof window !== 'undefined' && typeof window.localStorage !== 'undefined';
}

export function isDevApiSwitchEnabled() {
  return import.meta.env.DEV;
}

export function normalizeDevApiTarget(value: null | string | undefined): DevApiTarget {
  return value === DEV_API_TARGETS.prod
    ? DEV_API_TARGETS.prod
    : DEV_API_TARGETS.internal;
}

export function getStoredDevApiTarget(): DevApiTarget {
  if (!isDevApiSwitchEnabled() || !canUseStorage()) {
    return DEV_API_TARGETS.internal;
  }
  return normalizeDevApiTarget(
    window.localStorage.getItem(DEV_API_SWITCH_STORAGE_KEY),
  );
}

export function setStoredDevApiTarget(target: DevApiTarget) {
  if (!isDevApiSwitchEnabled() || !canUseStorage()) {
    return;
  }
  window.localStorage.setItem(
    DEV_API_SWITCH_STORAGE_KEY,
    normalizeDevApiTarget(target),
  );
}

export function getDevApiTargetLabel(target: DevApiTarget) {
  return (
    DEV_API_OPTIONS.find((item) => item.value === target)?.label ||
    '内网 API'
  );
}

export function getDevApiBaseURL(url?: string) {
  if (!isDevApiSwitchEnabled()) {
    return null;
  }
  const normalizedUrl = String(url || '');
  if (/^https?:\/\//.test(normalizedUrl)) {
    return null;
  }
  return DEV_API_PREFIX_MAP[getStoredDevApiTarget()];
}
