package casbin_service

import (
	"bwallet/models"
)

type CasbinRole struct {
	Id    int
	Ptype string
	V0    string
	V1    string
	V2    string
	V3    string
	V4    string
	V5    string
}

func (r *CasbinRole) GetAllRolesRelation() ([]*models.Role, error) {
	roles, err := models.GetRoles(r.getMaps())
	if err != nil {
		return nil, err
	}

	return roles, nil
}

func (r *CasbinRole) AddPolicy() error {
	role := map[string]interface{}{
		"ptype": r.Ptype,
		"v0":    r.V0,
		"v1":    r.V1,
	}

	if err := models.AddPolicy(role); err != nil {
		return err
	}

	return nil
}

func (r *CasbinRole) AddGroupingPolicy() error {
	permission := map[string]interface{}{
		"ptype": r.Ptype,
		"v0":    r.V0,
		"v1":    r.V1,
		"v2":    r.V2,
	}

	if err := models.AddGroupingPolicy(permission); err != nil {
		return err
	}

	return nil
}

func (r *CasbinRole) getMaps() (map[string]interface{}) {
	maps := make(map[string]interface{})

	if r.Id != 0 {
		maps["id"] = r.Id
	}

	if r.Ptype != "" {
		maps["ptype"] = r.Ptype
	}

	if r.V0 != "" {
		maps["v0"] = r.V0
	}

	if r.V1 != "" {
		maps["v1"] = r.V1
	}

	return maps
}
