package backend

import (
	"bwallet/pkg/errno"
	"bwallet/pkg/handler"
	"bwallet/pkg/util"
	"bwallet/service/casbin_service"
	"bwallet/validate_service"
	"github.com/gin-gonic/gin"
	"strings"
)

func GetAdminRoles(c *gin.Context) {

}

func AddAdminRole(c *gin.Context) {
	role := validate_service.AdminRole{}
	c.ShouldBindJSON(&role)

	if ok, errors := validate_service.ValidateInputs(role); !ok {
		for _, err := range errors {
			handler.SendResponse(c, errno.ErrBind, strings.Join(err, " "))
			return
		}
	}

	roleService := casbin_service.AdminRole{
		Uid:    role.Uid,
		RoleId: role.RoleId,
	}

	if err := roleService.AddAdminRole(); err != nil {
		handler.SendResponse(c, errno.ErrAddWallet, nil)
		return
	}

	handler.SendResponse(c, nil, nil)
}

func EditAdminRole(c *gin.Context) {

}

func DeleteAdminRole(c *gin.Context) {

}

func SetRole(c *gin.Context) {
	token := c.Request.Header.Get("Token")
	user, _ := util.ParseToken(token)
	group := user.UserInfo.Group

	if ("administrator" != group || "admin" != group) {
		handler.SendResponse(c, errno.ErrUserAuthIncorrect, nil)
		return
	}

	role := validate_service.SetRole{}
	c.ShouldBindJSON(&role)
	if ok, errors := validate_service.ValidateInputs(role); !ok {
		for _, err := range errors {
			handler.SendResponse(c, errno.ErrBind, strings.Join(err, " "))
			return
		}
	}

	casbin_service := casbin_service.CasbinRole{
		Ptype: role.Type,
		V0:    role.Value,
		V1:    role.AllowRole,
	}
	if err := casbin_service.AddPolicy(); err != nil {
		handler.SendResponse(c, errno.ErrAddCoin, nil)
		return
	}

	handler.SendResponse(c, nil, nil)
}

func SetPermission(c *gin.Context) {
	token := c.Request.Header.Get("Token")
	user, _ := util.ParseToken(token)
	group := user.UserInfo.Group

	if ("administrator" != group || "admin" != group) {
		handler.SendResponse(c, errno.ErrUserAuthIncorrect, nil)
		return
	}

	permission := validate_service.SetPermission{}
	c.ShouldBindJSON(&permission)
	if ok, errors := validate_service.ValidateInputs(permission); !ok {
		for _, err := range errors {
			handler.SendResponse(c, errno.ErrBind, strings.Join(err, " "))
			return
		}
	}

	casbin_service := casbin_service.CasbinRole{
		Ptype: permission.Type,
		V0:    permission.Value,
		//V1:    permission.Permission,
	}

	if err := casbin_service.AddGroupingPolicy(); err != nil {
		handler.SendResponse(c, errno.ErrAddCoin, nil)
		return
	}

	handler.SendResponse(c, nil, nil)
}
