package handler

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"

	"github.com/user-management-system/internal/domain"
	"github.com/user-management-system/internal/service"
)

// PermissionHandler handles permission management requests
type PermissionHandler struct {
	permissionService *service.PermissionService
}

// NewPermissionHandler creates a new PermissionHandler
func NewPermissionHandler(permissionService *service.PermissionService) *PermissionHandler {
	return &PermissionHandler{permissionService: permissionService}
}

// CreatePermission 创建权限
// @Summary 创建权限
// @Description 创建新的权限定义（仅管理员）
// @Tags 权限管理
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param request body service.CreatePermissionRequest true "权限信息"
// @Success 201 {object} Response{data=domain.Permission} "创建成功"
// @Failure 400 {object} Response "请求参数错误"
// @Failure 403 {object} Response "无权限"
// @Router /api/v1/permissions [post]
func (h *PermissionHandler) CreatePermission(c *gin.Context) {
	var req service.CreatePermissionRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": err.Error()})
		return
	}

	perm, err := h.permissionService.CreatePermission(c.Request.Context(), &req)
	if err != nil {
		handleError(c, err)
		return
	}

	c.JSON(http.StatusCreated, gin.H{
		"code":    0,
		"message": "success",
		"data":    perm,
	})
}

// ListPermissions 获取权限列表
// @Summary 获取权限列表
// @Description 获取系统权限列表
// @Tags 权限管理
// @Produce json
// @Security BearerAuth
// @Success 200 {object} Response{data=[]domain.Permission} "权限列表"
// @Router /api/v1/permissions [get]
func (h *PermissionHandler) ListPermissions(c *gin.Context) {
	var req service.ListPermissionRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": err.Error()})
		return
	}

	perms, _, err := h.permissionService.ListPermissions(c.Request.Context(), &req)
	if err != nil {
		handleError(c, err)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data":    perms,
	})
}

// GetPermission 获取权限详情
// @Summary 获取权限详情
// @Description 根据ID获取权限详细信息
// @Tags 权限管理
// @Produce json
// @Security BearerAuth
// @Param id path int true "权限ID"
// @Success 200 {object} Response{data=domain.Permission} "权限信息"
// @Failure 404 {object} Response "权限不存在"
// @Router /api/v1/permissions/{id} [get]
func (h *PermissionHandler) GetPermission(c *gin.Context) {
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "invalid permission id"})
		return
	}

	perm, err := h.permissionService.GetPermission(c.Request.Context(), id)
	if err != nil {
		handleError(c, err)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data":    perm,
	})
}

// UpdatePermission 更新权限
// @Summary 更新权限
// @Description 更新权限信息（仅管理员）
// @Tags 权限管理
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "权限ID"
// @Param request body service.UpdatePermissionRequest true "更新信息"
// @Success 200 {object} Response{data=domain.Permission} "更新成功"
// @Failure 400 {object} Response "请求参数错误"
// @Failure 403 {object} Response "无权限"
// @Failure 404 {object} Response "权限不存在"
// @Router /api/v1/permissions/{id} [put]
func (h *PermissionHandler) UpdatePermission(c *gin.Context) {
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "invalid permission id"})
		return
	}

	var req service.UpdatePermissionRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": err.Error()})
		return
	}

	perm, err := h.permissionService.UpdatePermission(c.Request.Context(), id, &req)
	if err != nil {
		handleError(c, err)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data":    perm,
	})
}

// DeletePermission 删除权限
// @Summary 删除权限
// @Description 删除权限定义（仅管理员）
// @Tags 权限管理
// @Produce json
// @Security BearerAuth
// @Param id path int true "权限ID"
// @Success 200 {object} Response "删除成功"
// @Failure 403 {object} Response "无权限"
// @Failure 404 {object} Response "权限不存在"
// @Router /api/v1/permissions/{id} [delete]
func (h *PermissionHandler) DeletePermission(c *gin.Context) {
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "invalid permission id"})
		return
	}

	if err := h.permissionService.DeletePermission(c.Request.Context(), id); err != nil {
		handleError(c, err)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "permission deleted",
	})
}

// UpdatePermissionStatus 更新权限状态
// @Summary 更新权限状态
// @Description 更新权限状态（enabled/disabled）（仅管理员）
// @Tags 权限管理
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "权限ID"
// @Param request body UpdatePermissionStatusRequest true "状态信息"
// @Success 200 {object} Response "状态更新成功"
// @Failure 400 {object} Response "无效的状态值"
// @Failure 403 {object} Response "无权限"
// @Failure 404 {object} Response "权限不存在"
// @Router /api/v1/permissions/{id}/status [put]
func (h *PermissionHandler) UpdatePermissionStatus(c *gin.Context) {
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "invalid permission id"})
		return
	}

	var req struct {
		Status string `json:"status" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": err.Error()})
		return
	}

	var status domain.PermissionStatus
	switch req.Status {
	case "enabled", "1":
		status = domain.PermissionStatusEnabled
	case "disabled", "0":
		status = domain.PermissionStatusDisabled
	default:
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "invalid status"})
		return
	}

	if err := h.permissionService.UpdatePermissionStatus(c.Request.Context(), id, status); err != nil {
		handleError(c, err)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "status updated",
	})
}

// GetPermissionTree 获取权限树
// @Summary 获取权限树
// @Description 获取系统权限的树形结构
// @Tags 权限管理
// @Produce json
// @Security BearerAuth
// @Success 200 {object} Response{data=[]domain.Permission} "权限树"
// @Router /api/v1/permissions/tree [get]
func (h *PermissionHandler) GetPermissionTree(c *gin.Context) {
	tree, err := h.permissionService.GetPermissionTree(c.Request.Context())
	if err != nil {
		handleError(c, err)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data":    tree,
	})
}
