package controller

import (
	"errors"
	"net/http"
	"strconv"

	"metazone.cc/metalab/internal/common"
	"metazone.cc/metalab/internal/model"

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

// Delete DELETE /api/comments/:id
func (ctrl *CommentController) Delete(c *gin.Context) {
	uid, role, ok := common.GetGinUser(c)
	if !ok {
		common.Error(c, http.StatusUnauthorized, "请先登录")
		return
	}

	commentID, err := strconv.ParseUint(c.Param("id"), 10, 64)
	if err != nil {
		common.Error(c, http.StatusBadRequest, "无效的评论ID")
		return
	}

	// 权限检查由 service 层统一处理
	isAdmin := model.HasMinRole(role, model.RoleAdmin)
	if err := ctrl.commentService.Delete(uint(commentID), uid, isAdmin); err != nil {
		if errors.Is(err, common.ErrPermissionDenied) {
			common.Error(c, http.StatusForbidden, err.Error())
			return
		}
		common.Error(c, http.StatusBadRequest, err.Error())
		return
	}

	common.OkMessage(c, "删除成功")
}

// SearchUsers GET /api/users/search?q=keyword
func (ctrl *CommentController) SearchUsers(c *gin.Context) {
	_, _, ok := common.GetGinUser(c)
	if !ok {
		common.Error(c, http.StatusUnauthorized, "请先登录")
		return
	}

	q := c.Query("q")
	if q == "" {
		common.Ok(c, []model.UserSearchResult{})
		return
	}

	users, err := ctrl.commentService.SearchUsers(q)
	if err != nil {
		common.Error(c, http.StatusInternalServerError, "搜索用户失败")
		return
	}

	common.Ok(c, users)
}
