package permissions

import (
	"testing"
)

// Mocking the service for logic test without DB
type MockPermissionService struct {
	cache map[string]*string // ID -> ParentID
}

func (m *MockPermissionService) getRoleAncestors(roleID string) []string {
	ancestors := []string{}
	curr := roleID
	for {
		parent, ok := m.cache[curr]
		if !ok || parent == nil {
			break
		}
		ancestors = append(ancestors, *parent)
		curr = *parent
	}
	return ancestors
}

// Copy of the NEW logic from sharing_rules.go
func (m *MockPermissionService) isUserInRoleOrAbove(userRoleID, targetRoleID *string) bool {
	if userRoleID == nil || targetRoleID == nil {
		return false
	}
	if *userRoleID == *targetRoleID {
		return true
	}

	// Check if user is ancestor of target (User is ABOVE target)
	// We need a helper for 'isUserAboveInHierarchy' logic here
	ancestorsOfTarget := m.getRoleAncestors(*targetRoleID)
	for _, ancestorID := range ancestorsOfTarget {
		if ancestorID == *userRoleID {
			return true
		}
	}
	return false
}

func TestSharingLogic_Direction(t *testing.T) {
	// Setup Hierarchy: CEO -> VP -> Manager -> Rep
	// IDs: role-ceo, role-vp, role-mgr, role-rep
	ceo := "role-ceo"
	vp := "role-vp"
	mgr := "role-mgr"
	rep := "role-rep"

	cache := map[string]*string{
		"role-rep": &mgr,
		"role-mgr": &vp,
		"role-vp":  &ceo,
		"role-ceo": nil,
	}

	svc := &MockPermissionService{cache: cache}

	// Scenario 1: Share with Manager. Does Rep get access?
	// Target: Manager. User: Rep.
	// New Logic: isUserInRoleOrAbove(Rep, Manager) -> Should be FALSE
	accessRep := svc.isUserInRoleOrAbove(&rep, &mgr)

	t.Logf("Share with Manager, Rep Access: %v", accessRep)

	if accessRep {
		t.Errorf("Security Risk PROVEN: Sharing with Manager leaked to Rep (Subordinate)")
	} else {
		t.Logf("Security Check Passed: Sharing with Manager did NOT leak to Rep")
	}

	// Scenario 2: Share with Rep. Does Manager get access?
	// Target: Rep. User: Manager.
	// New Logic: isUserInRoleOrAbove(Manager, Rep) -> Should be TRUE
	accessMgr := svc.isUserInRoleOrAbove(&mgr, &rep)
	t.Logf("Share with Rep, Manager Access: %v", accessMgr)

	if !accessMgr {
		t.Errorf("Functionality Issue: Manager should see Rep's shared data")
	}
}
