const asyncHandler = require('../utils/asyncHandler')
const { success } = require('../utils/response')
const {
    validateLoginBody,
    validateProfileEditBody,
} = require('../middlewares/validateWechatAuth')
const userService = require('../services/userService')

const login = asyncHandler(async (req, res) => {
    const payload = validateLoginBody(req.body)
    const data = await userService.authenticateWechatUser(payload)

    const messageMap = {
        register_success: '注册成功',
        login_success: '登录成功',
    }

    return success(res, messageMap[data.status] || '登录成功', data)
})

const updateProfile = asyncHandler(async (req, res) => {
    const payload = validateProfileEditBody(req.body)
    const data = await userService.updateWechatUserProfile(req.usersWxOpenid, payload)
    return success(res, '信息更新成功', data)
})

const refreshToken = asyncHandler(async (req, res) => {
    const data = await userService.refreshWechatToken(req.usersWxOpenid)
    return success(res, '刷新成功', data)
})

module.exports = {
    updateProfile,
    login,
    refreshToken,
}
