package handler

import (
	"errors"
	"strconv"

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

	"my-project/internal/model/dto"
	"my-project/internal/service"
	"my-project/pkg/common"
)

// UserHandler 用户相关API处理器
type UserHandler struct {
	userService *service.UserService
}

// NewUserHandler 创建用户Handler实例
// @param userService *service.UserService - 用户服务
// @return *UserHandler - Handler实例
func NewUserHandler(userService *service.UserService) *UserHandler {
	return &UserHandler{userService: userService}
}

// GetUserByID 根据ID获取用户信息
// @param c *gin.Context - GIN上下文
func (h *UserHandler) GetUserByID(c *gin.Context) {
	// 1. 参数解析
	idStr := c.Param("id")
	userID, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		common.ResponseError(c, common.CodeParamError, "用户ID格式错误")
		return
	}

	// 2. 调用Service
	user, err := h.userService.GetUserByID(c.Request.Context(), userID)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			common.ResponseError(c, common.CodeNotFound, "用户不存在")
			return
		}
		common.ResponseErrorWithDetail(c, common.CodeServerError, "获取用户失败", err)
		return
	}

	// 3. 成功响应
	common.ResponseSuccess(c, user)
}

// CreateUser 创建用户
// @param c *gin.Context - GIN上下文
func (h *UserHandler) CreateUser(c *gin.Context) {
	var req dto.CreateUserRequest

	if err := c.ShouldBindJSON(&req); err != nil {
		common.ResponseErrorWithDetail(c, common.CodeValidationFail, "参数验证失败", err)
		return
	}

	user, err := h.userService.CreateUser(c.Request.Context(), &req)
	if err != nil {
		common.ResponseErrorWithDetail(c, common.CodeBusiness, "创建用户失败", err)
		return
	}

	common.ResponseSuccessWithMessage(c, user, "用户创建成功")
}
