/*
Copyright (C) 2025 QuantumNous

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.

For commercial licensing, please contact support@quantumnous.com
*/

export function setStatusData(data) {
  localStorage.setItem('status', JSON.stringify(data));
  localStorage.setItem('system_name', data.system_name);
  localStorage.setItem('logo', data.logo);
  localStorage.setItem('footer_html', data.footer_html);
  localStorage.setItem('quota_per_unit', data.quota_per_unit);
  // 兼容：保留旧字段，同时写入新的额度展示类型
  localStorage.setItem('display_in_currency', data.display_in_currency);
  localStorage.setItem('quota_display_type', data.quota_display_type || 'USD');
  localStorage.setItem(
    'recharge_display_currency',
    data.recharge_display_currency || 'USD',
  );
  localStorage.setItem('enable_drawing', data.enable_drawing);
  localStorage.setItem('enable_task', data.enable_task);
  localStorage.setItem('enable_data_export', data.enable_data_export);
  localStorage.setItem('chats', JSON.stringify(data.chats));
  localStorage.setItem(
    'data_export_default_time',
    data.data_export_default_time,
  );
  localStorage.setItem(
    'default_collapse_sidebar',
    data.default_collapse_sidebar,
  );
  localStorage.setItem('mj_notify_enabled', data.mj_notify_enabled);
  localStorage.setItem(
    'model_default_docs_enabled',
    data.model_default_docs_enabled,
  );
  if (data.chat_link) {
    // localStorage.setItem('chat_link', data.chat_link);
  } else {
    localStorage.removeItem('chat_link');
  }
  if (data.chat_link2) {
    // localStorage.setItem('chat_link2', data.chat_link2);
  } else {
    localStorage.removeItem('chat_link2');
  }
  if (data.docs_link) {
    localStorage.setItem('docs_link', data.docs_link);
  } else {
    localStorage.removeItem('docs_link');
  }
  if (data.default_site_language) {
    localStorage.setItem('default_site_language', data.default_site_language);
  } else {
    localStorage.removeItem('default_site_language');
  }
}

/**
 * 解析 /api/status 中 `sms_verification_enabled` 的原始值，兼容字符串与数字，避免 `"false" !== false` 导致误判为开启。
 * @param {unknown} raw 原始字段值
 * @returns {boolean|undefined} 显式开/关；未提供或无法识别时为 undefined
 */
export function normalizeSmsVerificationEnabled(raw) {
  if (raw === true || raw === 'true' || raw === 1 || raw === '1') {
    return true;
  }
  if (raw === false || raw === 'false' || raw === 0 || raw === '0') {
    return false;
  }
  return undefined;
}

export function setUserData(data) {
  localStorage.setItem('user', JSON.stringify(data));
}

/**
 * 将 GET /api/user/self 返回的 data 合并进本地 user，并可选 dispatch 登录态。
 * 会去掉 permissions、sidebar_modules（与登录接口存库字段不一致）。
 */
export function mergeSelfResponseIntoLocalUser(data, dispatch) {
  if (!data || data.id == null) return;
  try {
    const { permissions: _p, sidebar_modules: _s, ...serverProfile } = data;
    let prev = {};
    const raw = localStorage.getItem('user');
    if (raw) prev = JSON.parse(raw);
    const nextUser = { ...prev, ...serverProfile };
    localStorage.setItem('user', JSON.stringify(nextUser));
    if (dispatch) {
      dispatch({ type: 'login', payload: nextUser });
    }
  } catch (e) {
    /* ignore */
  }
}
