// utils/login.js
import {
  applyWechatLoginData,
  backfillUserProfileCache,
  getSessionToken,
  isWechatLoginSuccess,
} from './role-tab-bar';

const app = getApp();

export function ensureLogin(options = {}) {
  const silent = options.silent !== false;
  const page = options.page || null;
  const token = getSessionToken(app);
  if (token) {
    backfillUserProfileCache(app);
    return Promise.resolve(true);
  }

  // 关键：如果已有登录流程正在执行，直接返回那个 Promise，避免并发登录
  if (app.globalData.loginPromise) {
    return app.globalData.loginPromise;
  }

  // 开始新的登录流程
  const loginPromise = new Promise(async (resolve, reject) => {
    if (silent) {
      wx.showLoading({ title: '自动登录中...', mask: true });
    }
    try {
      const loginRes = await wx.login();
      if (!loginRes.code) throw new Error('获取微信登录码失败');

      const apiBaseUrl = app.globalData.apiBaseUrl;
      if (!apiBaseUrl) throw new Error('服务器配置错误');

      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: apiBaseUrl + '/yonghu/wechatlogin',
          method: 'POST',
          data: { code: loginRes.code },
          header: { 'content-type': 'application/json' },
          success: resolve,
          fail: reject,
        });
      });

      const userData = res.data && (res.data.data || res.data);
      if (res.statusCode === 200 && isWechatLoginSuccess(res.data) && userData) {
        applyWechatLoginData(userData, page);
        resolve(true);
      } else {
        const msg = res.data?.msg || '登录失败';
        wx.showToast({ title: msg, icon: 'none' });
        reject(new Error(msg));
      }
    } catch (error) {
      wx.showToast({ title: error.message || '登录失败', icon: 'none' });
      reject(error);
    } finally {
      if (silent) wx.hideLoading();
    }
  });

  // 存储全局登录 Promise，供 request.js 感知
  app.globalData.loginPromise = loginPromise;
  // 无论成功或失败，完成后清空标记
  loginPromise.finally(() => {
    app.globalData.loginPromise = null;
  });

  return loginPromise;
}