// utils/login.js
import {
  applyWechatLoginData,
  backfillUserProfileCache,
  getSessionToken,
  isWechatLoginSuccess,
} from './role-tab-bar';
import { restoreStaffContextAfterAuth } from './staff-api.js';
import { CLUB_API, getClubId, setClubId, buildClubHeaders } from './club-context';

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);
    restoreStaffContextAfterAuth();
    return Promise.resolve(true);
  }

  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 clubId = getClubId(app);
      const appId = app.globalData.appId || '';

      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: apiBaseUrl + CLUB_API.wechatLogin,
          method: 'POST',
          data: { code: loginRes.code, club_id: clubId, app_id: appId },
          header: buildClubHeaders({ '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) {
        if (userData.club_id) {
          setClubId(userData.club_id, app);
        }
        applyWechatLoginData(userData, page);
        restoreStaffContextAfterAuth();
        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();
    }
  });

  app.globalData.loginPromise = loginPromise;
  loginPromise.finally(() => {
    app.globalData.loginPromise = null;
  });

  return loginPromise;
}
