package casbin_service

import (
	"bwallet/models"
)

type Role struct {
	Id          int32
	RoleName    string
	Description string
	PlatformId  int32
}

func (r *Role) GetRole() (*models.Role, error) {
	role, err := models.GetRole(r.Id)
	if err != nil {
		return nil, err
	}

	return role, nil
}

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

	return roles, nil
}

func (r *Role) AddRole() error {
	role := map[string]interface{}{
		"role_name":   r.RoleName,
		"description": r.Description,
		"platform_id": r.PlatformId,
	}

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

	return nil
}

func (r *Role) EditRole() error {
	return models.EditRole(r.Id, map[string]interface{}{
		"role_name":   r.RoleName,
		"description": r.Description,
	})
}

func (r *Role) DeleteRole() error {
	return models.DeleteRole(r.Id)
}

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

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

	if r.RoleName != "" {
		maps["role_name"] = r.RoleName
	}

	if r.Description != "" {
		maps["description"] = r.Description
	}

	if r.PlatformId != 0 {
		maps["platform_id"] = r.PlatformId
	}

	return maps
}
