/**
 * 多俱乐部上下文（读取 config/club-config.js 中的固定 club_id）
 */
import { CLUB_ID as CONFIG_CLUB_ID, WX_APP_ID } from '../config/club-config';

const CLUB_ID_KEY = 'club_id';
const CLUB_SCOPE_KEY = 'club_scope';
const DEFAULT_CLUB_ID = CONFIG_CLUB_ID || 'xq';

export const CLUB_API = {
  wechatLogin: '/jituan/auth/wechat-login',
  dashouRegister: '/jituan/auth/dashou-register',
  clubList: '/jituan/club/list',
};

export function getConfiguredClubId() {
  return DEFAULT_CLUB_ID;
}

export function getWxAppId() {
  return WX_APP_ID || '';
}

export function getClubId(app) {
  const configured = getConfiguredClubId();
  const stored = wx.getStorageSync(CLUB_ID_KEY);
  if (stored && stored === configured) {
    return stored;
  }
  if (stored && stored !== configured) {
    wx.removeStorageSync(CLUB_ID_KEY);
  }
  app = app || getApp();
  if (app && app.globalData && app.globalData.clubId === configured) {
    return app.globalData.clubId;
  }
  return configured;
}

export function setClubId(clubId, app) {
  const configured = getConfiguredClubId();
  const id = (clubId || configured).trim() || configured;
  if (id !== configured) {
    console.warn('[club] 登录返回 club_id 与工程配置不一致，以工程配置为准', id, configured);
  }
  const finalId = configured;
  app = app || getApp();
  wx.setStorageSync(CLUB_ID_KEY, finalId);
  if (app && app.globalData) {
    app.globalData.clubId = finalId;
  }
  return finalId;
}

export function getClubScope() {
  return wx.getStorageSync(CLUB_SCOPE_KEY) || 'single';
}

export function buildClubHeaders(extra = {}) {
  return {
    ...extra,
    'X-Club-Id': getClubId(),
  };
}
