import { defineOverridesPreferences } from '@easyflow/preferences';

const assetBase = import.meta.env.BASE_URL || '/';

/**
 * @description 项目配置文件
 * 只需要覆盖项目中的一部分配置，不需要的配置不用覆盖，会自动使用默认配置
 * !!! 更改配置后请清空缓存，否则可能不生效
 */
export const overridesPreferences = defineOverridesPreferences({
  // overrides
  app: {
    name: import.meta.env.VITE_APP_TITLE,
    accessMode: 'mixed',
  },
  auth: {
    sloganImage: `${assetBase}slogan.svg`,
  },
  logo: {
    source: `${assetBase}logo.svg`,
    sourceDark: `${assetBase}logoDark.svg`,
    sourceMini: `${assetBase}logoMini.svg`,
    sourceMiniDark: `${assetBase}logoMiniDark.svg`,
  },
  transition: {
    enable: false,
    loading: false,
    progress: false,
  },
});

const BUILTIN_BRAND_ASSETS = new Map([
  ['/logo.svg', 'logo.svg'],
  ['/logoDark.svg', 'logoDark.svg'],
  ['/logoMini.svg', 'logoMini.svg'],
  ['/logoMiniDark.svg', 'logoMiniDark.svg'],
  ['/slogan.svg', 'slogan.svg'],
]);

function normalizeBuiltinBrandAsset(path?: string) {
  if (!path) {
    return path;
  }

  const fileName = BUILTIN_BRAND_ASSETS.get(path);
  if (!fileName) {
    return path;
  }

  return `${assetBase}${fileName}`;
}

export function normalizeBrandAssetPreferences(preferences: {
  auth?: { sloganImage?: string };
  logo?: {
    source?: string;
    sourceDark?: string;
    sourceMini?: string;
    sourceMiniDark?: string;
  };
}) {
  const normalized = {
    auth: {
      sloganImage: normalizeBuiltinBrandAsset(preferences.auth?.sloganImage),
    },
    logo: {
      source: normalizeBuiltinBrandAsset(preferences.logo?.source),
      sourceDark: normalizeBuiltinBrandAsset(preferences.logo?.sourceDark),
      sourceMini: normalizeBuiltinBrandAsset(preferences.logo?.sourceMini),
      sourceMiniDark: normalizeBuiltinBrandAsset(
        preferences.logo?.sourceMiniDark,
      ),
    },
  };

  const changed =
    normalized.auth.sloganImage !== preferences.auth?.sloganImage ||
    normalized.logo.source !== preferences.logo?.source ||
    normalized.logo.sourceDark !== preferences.logo?.sourceDark ||
    normalized.logo.sourceMini !== preferences.logo?.sourceMini ||
    normalized.logo.sourceMiniDark !== preferences.logo?.sourceMiniDark;

  return {
    changed,
    normalized,
  };
}
