import request from '../utils/request';

/**
 * 用户注册（使用手机号，无需验证码）
 * @param {string} phone - 手机号（11位）
 * @param {string} password - 密码
 * @param {string} nickname - 昵称（可选）
 */
export const register = async (phone, password, nickname = '') => {
  try {
    const response = await request.post('/auth/register', {
      phone,
      password,
      nickname
    });
    
    // 保存 Token 和用户信息
    localStorage.setItem('access_token', response.access_token);
    localStorage.setItem('user_info', JSON.stringify(response.user));
    
    return {
      success: true,
      data: response
    };
  } catch (error) {
    return {
      success: false,
      message: error.message
    };
  }
};

/**
 * 用户登录（使用手机号）
 * @param {string} phone - 手机号
 * @param {string} password - 密码
 */
export const login = async (phone, password) => {
  try {
    const response = await request.post('/auth/login', {
      phone,
      password
    });
    
    // 保存 Token 和用户信息
    localStorage.setItem('access_token', response.access_token);
    localStorage.setItem('user_info', JSON.stringify(response.user));
    
    return {
      success: true,
      data: response
    };
  } catch (error) {
    return {
      success: false,
      message: error.message
    };
  }
};

/**
 * 退出登录
 */
export const logout = () => {
  localStorage.removeItem('access_token');
  localStorage.removeItem('user_info');
  window.location.reload();
};

/**
 * 获取当前用户信息
 */
export const getCurrentUser = () => {
  const userInfo = localStorage.getItem('user_info');
  return userInfo ? JSON.parse(userInfo) : null;
};

/**
 * 检查是否已登录
 */
export const isLoggedIn = () => {
  return !!localStorage.getItem('access_token');
};
