package middleware

import (
	"gadmin/config"
	"gadmin/internal/admin/consts"
	"gadmin/internal/gorm/query"
	"gadmin/utility/serializer"
	"gadmin/utility/token"
	"github.com/gin-gonic/gin"
)

// Permission 验证权限
func Permission() gin.HandlerFunc {
	return func(c *gin.Context) {

		q := query.Use(config.AdminDB).AdminUser

		userId := token.GetUID(c)
		if userId <= 0 {
			c.JSON(200, serializer.Err(consts.CodeNoPermission, "用户信息获取失败", nil))
			c.Abort()
		}

		c.Set("admin_id", userId)

		models, err := q.WithContext(c).Where(q.ID.Eq(userId)).First()
		if err != nil {
			c.JSON(200, serializer.Err(consts.CodeNoPermission, err.Error(), err))
			c.Abort()
			return
		}

		if models == nil {
			c.JSON(200, serializer.Err(consts.CodeNoPermission, "用户不存在", nil))
			c.Abort()
			return
		}

		if models.Status != 1 {
			c.JSON(200, serializer.Err(consts.CodeCheckLogin, "账号已被禁用", nil))
			c.Abort()
			return
		}
		c.Set("admin_role_id", int64(models.RoleID))
		if models.UserName != "mojun" {
			if err := config.ValidityAuth(int64(models.RoleID), c.Request.Method, c.Request.URL.Path); err != nil {
				c.JSON(200, serializer.Err(consts.CodeNoPermission, err.Error(), err))
				c.Abort()
				return
			}
		}

		c.Next()
		return
	}
}
