/**
 * 认证服务
 * 处理登录、注册、验证码等认证相关接口
 * 与Web端(life-script/src/services/auth.js)保持一致
 */

import { get, post } from './request.js'

/**
 * 获取短信验证码
 * @param {string} phone - 手机号
 * @returns {Promise<Object>} 验证码响应
 */
export const getSmsCode = async (phone) => {
  const response = await get('/auth/sms-code', { 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 post('/auth/login', { phone, smsCode })
  
  // 保存token
  if (response.data) {
    const { accessToken, refreshToken } = response.data
    if (accessToken) {
      uni.setStorageSync('access_token', accessToken)
    }
    if (refreshToken) {
      uni.setStorageSync('refresh_token', refreshToken)
    }
  }
  
  return response
}

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

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

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

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

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

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