import api from './api';

/**
 * 认证服务
 * 处理登录、注册、验证码等认证相关接口
 */

/**
 * 获取短信验证码
 * @param {string} phone - 手机号
 * @returns {Promise<Object>} 验证码响应
 */
export const getSmsCode = async (phone) => {
  const response = await api.get('/auth/sms-code', {
    params: { phone }
  });
  return response;
};

/**
 * 用户登录（手机号 + 验证码）
 * @param {Object} params - 登录参数
 * @param {string} params.phone - 手机号
 * @param {string} params.smsCode - 短信验证码
 * @returns {Promise<Object>} 登录响应（包含 token）
 */
export const login = async ({ phone, smsCode }) => {
  const response = await api.post('/auth/login', {
    phone,
    smsCode
  });
  
  // 保存 token
  if (response.data) {
    const { accessToken, refreshToken } = response.data;
    if (accessToken) {
      localStorage.setItem('access_token', accessToken);
    }
    if (refreshToken) {
      localStorage.setItem('refresh_token', refreshToken);
    }
  }
  
  return response;
};

/**
 * 用户登出
 * @returns {Promise<void>}
 */
export const logout = async () => {
  try {
    await api.post('/auth/logout');
  } finally {
    // 无论成功失败都清除本地 token
    localStorage.removeItem('access_token');
    localStorage.removeItem('refresh_token');
  }
};

/**
 * 刷新 token
 * @returns {Promise<Object>} 新的 token
 */
export const refreshToken = async () => {
  const refreshToken = localStorage.getItem('refresh_token');
  if (!refreshToken) {
    throw new Error('No refresh token');
  }
  
  const response = await api.post('/auth/refreshToken', {
    refreshToken
  });
  
  // 更新 token
  if (response.data) {
    const { accessToken, refreshToken: newRefreshToken } = response.data;
    if (accessToken) {
      localStorage.setItem('access_token', accessToken);
    }
    if (newRefreshToken) {
      localStorage.setItem('refresh_token', newRefreshToken);
    }
  }
  
  return response;
};

/**
 * 验证 token 是否有效
 * @returns {Promise<boolean>}
 */
export const validateToken = async () => {
  try {
    const response = await api.get('/auth/validateToken');
    return response.data === true;
  } catch {
    return false;
  }
};

/**
 * 获取当前用户信息
 * @returns {Promise<Object>} 用户信息
 */
export const getCurrentUserInfo = async () => {
  const response = await api.get('/auth/userInfo');
  return response;
};

/**
 * 检查手机号是否已注册
 * @param {string} phone - 手机号
 * @returns {Promise<boolean>}
 */
export const checkPhone = async (phone) => {
  const response = await api.get('/auth/checkPhone', {
    params: { phone }
  });
  return response.data;
};

export default {
  getSmsCode,
  login,
  logout,
  refreshToken,
  validateToken,
  getCurrentUserInfo,
  checkPhone
};
