import { preferencesManager } from '@vben/preferences';

import {
  getPortalUiConfig,
  savePortalUiConfig,
} from '#/api/system/portal-ui-config';

/** 门户字号配置（与 infra_config 参数表对应） */
export interface PortalFontConfig {
  homeFontSize: number;
  menuFontSize: number;
}

/**
 * 从数据库读取全局字号配置并写入偏好设置。
 *
 * 读取成功后返回实际生效的配置，供调用方记录基线、避免回写。
 * 读取失败（未登录 / 后端不可用）返回 null，保持本地偏好不变。
 */
export async function loadPortalUiConfig(): Promise<null | PortalFontConfig> {
  try {
    const config = await getPortalUiConfig();
    preferencesManager.updatePreferences({
      app: { homeFontSize: config.homeFontSize },
      navigation: { fontSize: config.menuFontSize },
    });
    return config;
  } catch {
    return null;
  }
}

/** 将字号配置保存到数据库（全局） */
export async function savePortalUiConfigToServer(config: PortalFontConfig) {
  await savePortalUiConfig(config);
}
