package authorization

import (
	"fmt"

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

func isAChildOrganization(potentialParent viewmodel.Organization, potentialChild viewmodel.Organization) bool {
	for _, org := range potentialParent.ChildOrgs {
		if potentialChild.UUID == org.UUID {
			return true
		}
	}
	return false
}

func isSameOrganization(organizationA viewmodel.Organization, organizationB viewmodel.Organization) bool {
	return organizationA.UUID == organizationB.UUID
}

func grabOrgFromUser(user viewmodel.User) (viewmodel.Organization, error) {
	if len(user.Profiles) < 1 {
		return viewmodel.Organization{}, fmt.Errorf("User has no organizations %v", user)
	}

	return user.Profiles[0].Organization, nil
}

func grabOrgFromUserDirectly(user viewmodel.User) (viewmodel.Organization, error) {
	if len(user.Organizations) < 1 {
		return viewmodel.Organization{}, fmt.Errorf("User has no organizations %v", user)
	}

	return user.Organizations[0], nil
}

func CanCreateOrganization(user viewmodel.User, organization viewmodel.Organization ) bool {
	userRole, err := grabProfileFromUser(user)
	if err != nil {
		return false
	}

	/*
	Admin			BCBSI 
	Admin			Technical Support
	Super Admin 	Technical Support
	
	Manage all Organizations*/
	if userRole.Key == bcbsiAdmin || userRole.Key == brighterDevAdmin || userRole.Key == superAdmin{
		return true
	}

	userOrg, err := grabOrgFromUser(user)
	if err != nil{
		return false
	}
	
	/*
	Admin		Provider
	Admin		Plan
	
	Manage the authenticated Authorized User's Organization and child Organizations */
	if userRole.Key == providerAdmin || userRole.Key == planAdmin{
		if isSameOrganization(userOrg, organization) || isAChildOrganization(userOrg, organization) {
			return true
		}
		return false
	}
	
	return false
}

func CanUpdateOrganization(user viewmodel.User, organization viewmodel.Organization) bool{
	return CanCreateOrganization(user, organization)
}
