package user

import (
	"errors"
	"strings"

	"hfb_sys/backend/internal/middleware"
	"hfb_sys/backend/internal/modules/auth"
	"hfb_sys/backend/pkg/response"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type Handler struct {
	users *auth.UserRepository
}

type UpdateProfileRequest struct {
	Nickname  string `json:"nickname"`
	AvatarURL string `json:"avatar_url"`
}

func NewHandler(users *auth.UserRepository) *Handler {
	return &Handler{users: users}
}

func (h *Handler) Me(c *gin.Context) {
	if h.users == nil {
		response.ServiceUnavailable(c, "数据库未连接")
		return
	}
	userID, ok := c.Get(middleware.ContextUserID)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}
	user, err := h.users.FindByID(userID.(uint64))
	if errors.Is(err, gorm.ErrRecordNotFound) {
		response.Unauthorized(c, "用户不存在")
		return
	}
	if err != nil {
		response.ServiceUnavailable(c, "用户查询失败")
		return
	}
	response.OK(c, user)
}

func (h *Handler) UpdateMe(c *gin.Context) {
	if h.users == nil {
		response.ServiceUnavailable(c, "数据库未连接")
		return
	}
	userID, ok := c.Get(middleware.ContextUserID)
	if !ok {
		response.Unauthorized(c, "缺少用户上下文")
		return
	}

	var req UpdateProfileRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "资料格式不正确")
		return
	}

	nickname := strings.TrimSpace(req.Nickname)
	avatarURL := strings.TrimSpace(req.AvatarURL)
	if nickname == "" {
		response.BadRequest(c, "昵称不能为空")
		return
	}
	if len([]rune(nickname)) > 24 {
		response.BadRequest(c, "昵称不能超过 24 个字符")
		return
	}
	if len(avatarURL) > 512 {
		response.BadRequest(c, "头像地址过长")
		return
	}

	user, err := h.users.UpdateProfile(userID.(uint64), nickname, avatarURL)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		response.Unauthorized(c, "用户不存在")
		return
	}
	if err != nil {
		response.ServiceUnavailable(c, "资料更新失败")
		return
	}
	response.OK(c, user)
}
