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 group != "administrator" {
		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{
		V0: role.Value,
		V1: role.AllowRole,
	}
	if err := casbin_service.AddGroupingPolicy(); 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 group != "administrator" {
		handler.SendResponse(c, errno.ErrUserAuthIncorrect, nil)
		return
	}

	var permission casbin_service.SetPermission
	_ = c.ShouldBindJSON(&permission)

	casbin_service := casbin_service.SetPermission{
		Value: permission.Value,
		AllowPermissions: permission.AllowPermissions,
	}

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

	handler.SendResponse(c, nil, nil)
}
