# BG Builders - Assign Exchange Administrator role to Claude-MSP-Access service principal
# Required for Exchange Online app-only auth (Set-Mailbox, litigation hold, etc.)
# Run from interactive PowerShell as sysadmin@bgbuildersllc.com

$tenantId = "ededa4fb-f6eb-4398-851d-5eb3e11fab27"
$spId = "9c04bb74-c2d0-4d83-ab54-9c43a9daaa23"  # Claude-MSP-Access SP in BG Builders
$exoRoleId = "87706939-e519-4028-a73e-a6a7f04b4a20"  # Exchange Administrator

Write-Output "Connecting to Graph..."
Import-Module Microsoft.Graph.Authentication
Import-Module Microsoft.Graph.Identity.DirectoryManagement
Connect-MgGraph -TenantId $tenantId -Scopes 'RoleManagement.ReadWrite.Directory' -NoWelcome
Write-Output "[OK] Connected"

Write-Output "Assigning Exchange Administrator to Claude-MSP-Access..."
$body = @{
    "@odata.id" = "https://graph.microsoft.com/v1.0/servicePrincipals/$spId"
}
New-MgDirectoryRoleMemberByRef -DirectoryRoleId $exoRoleId -BodyParameter $body
Write-Output "[OK] Exchange Administrator role assigned"

# Now set litigation hold on Lesley
Write-Output "`nConnecting to Exchange Online..."
Import-Module ExchangeOnlineManagement
Connect-ExchangeOnline -UserPrincipalName "sysadmin@bgbuildersllc.com" -ShowBanner:$false
Write-Output "[OK] Connected"

Write-Output "Setting litigation hold on Lesley's mailbox..."
Set-Mailbox -Identity "lesley@bgbuildersllc.com" -LitigationHoldEnabled $true -LitigationHoldDuration Unlimited
Write-Output "[OK] Litigation hold enabled"

Write-Output "`nVerifying..."
Get-Mailbox -Identity "lesley@bgbuildersllc.com" | Format-List DisplayName,LitigationHoldEnabled,LitigationHoldDuration

Disconnect-ExchangeOnline -Confirm:$false
Disconnect-MgGraph
Write-Output "[OK] Done"
