package auth

import (
	"context"
	"errors"
	"fmt"
	"github.com/tidbcloud/tiinf/monitor/tilog"
)

type (
	RoleScope string
)

const (
	RoleScopeOrg     RoleScope = "ORG"
	RoleScopeProject RoleScope = "PROJECT"
)

var (
	OrgRoleMap = map[string]int{
		"org:owner":         1,
		"org:billing_admin": 2,
		"org:audit_admin":   2,
		"org:member":        3,
	}

	ProjectRoleMap = map[string]int{
		"project:owner":    1,
		"project:dev":      2,
		"project:readonly": 3,
	}
)

//
// CompareRoleLevels
//  @Description: roleA level is greater than the roleB level
//    -1： roleA < roleB
//     0： roleA = roleB
//     1： roleA > roleB
//  @Author wangletian 2024-03-13 21:38:33
//  @param roleScope
//  @param roleA
//  @param roleB
//  @return bool
//
func CompareRoleLevels(ctx context.Context, roleScope RoleScope, roleA, roleB string) (int, error) {

	result := 0
	if roleA == roleB {
		return result, nil
	}
	var roleMap map[string]int

	if roleScope == RoleScopeOrg {
		roleMap = OrgRoleMap
	} else if roleScope == RoleScopeProject {
		roleMap = ProjectRoleMap
	}

	if _, ok := roleMap[roleA]; !ok {
		msg := fmt.Sprintf("%s is invalid", roleA)
		tilog.Info(ctx, msg)
		return result, errors.New(msg)
	}

	if _, ok := roleMap[roleB]; !ok {
		msg := fmt.Sprintf("%s is invalid", roleB)
		tilog.Info(ctx, msg)
		return result, errors.New(fmt.Sprintf("%s is invalid", roleB))
	}

	sub := roleMap[roleB] - roleMap[roleA]
	if sub > 0 {
		//  roleA level >  roleB
		result = 1
	} else if sub < 0 {
		//  roleA level <  roleB
		result = -1
	}
	return result, nil
}
