package user

import (
	"fmt"
	"mini_server/internal/dao"
	"mini_server/internal/server/help"
	"mini_server/internal/server/httpreply"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

type ChangeAvatarIdRequest struct {
	AvatarId string `json:"avatar_id" binding:"min=1"` // 修改的头像id
}

func ChangeAvatarId(c *gin.Context) {
	reply := httpreply.NewDefaultReplyData()
	defer httpreply.Reply(c, reply)

	//解析请求参数
	var request ChangeAvatarIdRequest
	if err := c.ShouldBindJSON(&request); err != nil {
		reply.Status = http.StatusBadRequest
		reply.Message = fmt.Sprintf("invalid json data, err:%v", err)
		return
	}

	userId, ok := help.GetUserId(c)
	if !ok {
		reply.Status = http.StatusNotFound
		reply.Message = "无法获取用户信息"
		return
	}

	logrus.Tracef("修改用户头像，userId:%d,请求参数:%v", userId, request)

	if err := dao.User_Change_AvatarId(userId, request.AvatarId); err != nil {
		logrus.Errorf("更新用户头像失败，userId:%d,err:%v", userId, err)
		reply.Status = http.StatusInternalServerError
		reply.Message = "更新用户头像失败"
		return
	}

	full_lastest_userinfo(reply, userId)
}
