const { request } = require('./request');

const login = async (userInfo) => {
  const codeRes = await new Promise((resolve, reject) => {
    wx.login({
      success: resolve,
      fail: reject
    });
  });

  const code = codeRes.code;
  const res = await request({
    url: '/api/auth/wx-login',
    method: 'POST',
    data: { code, userInfo: userInfo || null }
  });

  const body = res.data || {};
  if (!body.success) {
    throw new Error(body.error || '登录失败');
  }

  const token = body.data?.token || '';
  if (!token) {
    throw new Error('登录失败：缺少 token');
  }

  wx.setStorageSync('auth_token', token);
  const app = getApp();
  if (app?.globalData) app.globalData.token = token;
  return body.data?.user || null;
};

const fetchMe = async () => {
  try {
    const res = await request({ url: '/api/auth/me', method: 'GET' });
    const body = res.data || {};
    if (!body.success) throw new Error(body.message || '获取用户信息失败');
    return body.data;
  } catch (e) {
    const msg = e?.userMessage || e?.message || '获取用户信息失败';
    const err = new Error(msg);
    err.baseUrl = e?.baseUrl;
    throw err;
  }
};

module.exports = {
  login,
  fetchMe
};
