package handlers

import (
	"fmt"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/niangaodev/art-code/models"
	"github.com/niangaodev/art-code/repositories"
	"github.com/niangaodev/art-code/utils"
)

// AdminGetRoles 获取所有角色
func AdminGetRoles(c *gin.Context) {
	roles, err := repositories.GetRoles()
	if err != nil {
		utils.ServerError(c, err)
		return
	}
	if roles == nil {
		utils.Success(c, []interface{}{})
	} else {
		utils.Success(c, roles)
	}
}

// AdminCreateRole 创建角色
func AdminCreateRole(c *gin.Context) {
	var role models.Role
	if err := c.ShouldBindJSON(&role); err != nil {
		utils.Error(c, 400, "Invalid request")
		return
	}

	if err := repositories.CreateRole(&role); err != nil {
		utils.ServerError(c, err)
		return
	}

	utils.SuccessWithMsg(c, "Role created successfully", gin.H{"id": role.ID})
}

// AdminUpdateRole 更新角色
func AdminUpdateRole(c *gin.Context) {
	idStr := c.Param("id")
	var id uint
	if _, err := fmt.Sscanf(idStr, "%d", &id); err != nil {
		utils.Error(c, 400, "Invalid role ID")
		return
	}

	var role models.Role
	if err := c.ShouldBindJSON(&role); err != nil {
		utils.Error(c, 400, "Invalid request")
		return
	}
	role.ID = id

	if err := repositories.UpdateRole(&role); err != nil {
		utils.ServerError(c, err)
		return
	}

	utils.SuccessWithMsg(c, "Role updated successfully", nil)
}

// AdminDeleteRole 删除角色
func AdminDeleteRole(c *gin.Context) {
	idStr := c.Param("id")
	var id uint
	if _, err := fmt.Sscanf(idStr, "%d", &id); err != nil {
		utils.Error(c, 400, "Invalid role ID")
		return
	}

	if err := repositories.DeleteRole(id); err != nil {
		utils.ServerError(c, err)
		return
	}

	utils.SuccessWithMsg(c, "Role deleted successfully", nil)
}

// AdminGetPermissions 获取所有权限
func AdminGetPermissions(c *gin.Context) {
	permissions, err := repositories.GetPermissions()
	if err != nil {
		utils.ServerError(c, err)
		return
	}
	if permissions == nil {
		utils.Success(c, []interface{}{})
	} else {
		utils.Success(c, permissions)
	}
}

// 更新角色权限请求结构
type UpdateRolePermissionsRequest struct {
	PermissionIDs []uint `json:"permissionIds" binding:"required"`
}

// 更新角色的权限
func AdminUpdateRolePermissions(c *gin.Context) {
	roleIDStr := c.Param("id")

	// 转换角色ID
	var roleID uint
	id, err := strconv.ParseUint(roleIDStr, 10, 32)
	if err != nil {
		utils.Error(c, 400, "Invalid role ID")
		return
	}
	roleID = uint(id)

	// 绑定请求数据
	var req UpdateRolePermissionsRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Error(c, 400, "Invalid request format")
		return
	}

	// 检查角色是否存在
	role, err := repositories.GetRoleByID(roleID)
	if err != nil {
		utils.ServerError(c, err)
		return
	}
	if role == nil {
		utils.Error(c, 404, "Role not found")
		return
	}

	// 更新权限
	if err := repositories.AssignPermissionsToRole(roleID, req.PermissionIDs); err != nil {
		utils.ServerError(c, err)
		return
	}

	utils.SuccessWithMsg(c, "Role permissions updated successfully", nil)
}
