package perm

import (
	"exam_system/dao"
	"exam_system/entity"
	result "exam_system/result"
	"exam_system/vo"
	"net/http"
	"regexp"
	"strings"

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

func Perm() gin.HandlerFunc {
	return func(c *gin.Context) {
		if strings.HasPrefix(c.Request.RequestURI, "/auth") {
			c.Next()
			return
		}
		id := c.GetInt("id")
		if id == 0 {
			c.JSON(http.StatusForbidden, result.NO_PERMISSION)
			c.Abort()
			return
		}

		// 查user
		res := dao.FindUserbyId(id)
		if res.Data == nil {
			c.JSON(http.StatusForbidden, result.USER_IS_NOT_EXISTED)
			c.Abort()
			return
		}
		userVo := res.Data.(vo.UserVo)

		// TODO 后续role和perm可以保存到redis里面
		// 查role列表
		roles := dao.FindRoleByUserId(userVo.ID)
		roleIds := make([]int, len(roles))
		for i, v := range roles {
			roleIds[i] = v.Id
		}

		// 查perm列表
		res = dao.FindPermByRoles(roleIds)
		if res.Code != result.SUCCESS.Code {
			c.JSON(http.StatusForbidden, res)
			c.Abort()
			return
		}
		permissions := res.Data.([]*entity.Perm)

		for _, permission := range permissions {
			match, _ := regexp.MatchString(permission.Path, c.Request.RequestURI)
			if match && strings.ToUpper(permission.Method) == c.Request.Method {
				c.Next()
				return
			}
		}

		c.JSON(http.StatusForbidden, result.NO_PERMISSION)
		c.Abort()
		return
	}
}
