package authorization

import "bitbucket.org/nemt/nemt-portal-api/application/viewmodel"

/*
CanCreateUser returns true if currentUser is allowed to create updatingUser according to
authorization rules
*/
func CanCreateUser(currentUser viewmodel.User, updatingUser viewmodel.User) bool {

	if len(currentUser.Profiles) < 1 {
		return false
	}

	if len(updatingUser.Profiles) < 1 {
		return false
	}

	currentUserOrganization, err := grabOrgFromUser(currentUser)
	if err != nil {
		return false
	}

	updatingUserOrganization, err := grabOrgFromUserDirectly(updatingUser)
	if err != nil {
		return false
	}

	currentUserRole, err := grabProfileFromUser(currentUser)
	if err != nil {
		return false
	}

	updatingUserRole, err := grabProfileFromUser(updatingUser)
	if err != nil {
		return false
	}

	/*
		Admin	Provider
		Manage all Authorized Users of the provider Organization or child organization

		The (Provider) Admin can manage Authorized Users of their Parent/ Top-level Org , but not Admins
	*/

	currentUserHigherOrEqualOrg := isSameOrganization(currentUserOrganization, updatingUserOrganization) || isAChildOrganization(currentUserOrganization, updatingUserOrganization)
	currentUserLowerOrg := isAChildOrganization(updatingUserOrganization, currentUserOrganization)
	if currentUserRole.Key == providerAdmin && currentUserHigherOrEqualOrg && equallyOrMorePrivileged(currentUserRole, updatingUserRole) {
		return true
	}
	if currentUserRole.Key == providerAdmin && currentUserLowerOrg && lessPrivilegedThanAdmin(updatingUserRole) {
		return true
	}

	/* Admin	BCBSI
	Manage all Authorized Users except Admins

	return false
	*/

	if currentUserRole.Key == bcbsiAdmin && lessPrivilegedThanAdmin(updatingUserRole) {
		return true
	}

	/* Admin	Technical Support	Manage all Authorized Users except Admins */

	if currentUserRole.Key == brighterDevAdmin && lessPrivilegedThanAdmin(updatingUserRole) {
		return true
	}

	/* Admin	Plan	Manage all Authorized Users of a single participating Plan except Admins */

	if currentUserRole.Key == planAdmin && lessPrivilegedThanAdmin(updatingUserRole) && isSameOrganization(currentUserOrganization, updatingUserOrganization) {
		return true
	}

	/* Super Admin	Technical Support
	Manage all Members, INCLUDING Admins */

	if currentUserRole.Key == superAdmin {
		return true
	}

	return false

}
