# BG Builders - Re-enable Lesley Roth + Add Shelly Delegate
# lesley@bgbuildersllc.com - was terminated 2026-02-27
# Actions:
#   1. Unblock sign-in
#   2. Reassign license
#   3. Add Shelly@bgbuildersllc.com as delegate (FullAccess + SendAs)
#   4. Enable litigation hold (prevent email deletion)

$ErrorActionPreference = "Stop"
$tenantId = "ededa4fb-f6eb-4398-851d-5eb3e11fab27"
$lesleyUPN = "lesley@bgbuildersllc.com"
$shellyUPN = "Shelly@bgbuildersllc.com"

Write-Output "========================================="
Write-Output " BG Builders - Re-enable Lesley Roth"
Write-Output " $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
Write-Output "========================================="

# --- STEP 1: Connect to Microsoft Graph ---
Write-Output "`n[STEP 1] Connecting to Microsoft Graph..."
Import-Module Microsoft.Graph.Authentication
Import-Module Microsoft.Graph.Users
Connect-MgGraph -TenantId $tenantId -Scopes 'User.ReadWrite.All','Organization.Read.All' -NoWelcome
Write-Output "[OK] Connected to Graph"

$lesley = Get-MgUser -UserId $lesleyUPN -Property Id,DisplayName,AccountEnabled,AssignedLicenses
Write-Output "[INFO] Lesley current state: AccountEnabled=$($lesley.AccountEnabled)"

# --- STEP 2: Unblock sign-in ---
Write-Output "`n[STEP 2] Unblocking sign-in..."
Update-MgUser -UserId $lesley.Id -AccountEnabled:$true
Write-Output "[OK] Sign-in unblocked for Lesley Roth"

# --- STEP 3: Reassign license ---
Write-Output "`n[STEP 3] Reassigning license..."
# List available SKUs to find the right one
$skus = Get-MgSubscribedSku -All
Write-Output "Available licenses:"
foreach ($sku in $skus) {
    $available = $sku.PrepaidUnits.Enabled - $sku.ConsumedUnits
    Write-Output "  $($sku.SkuPartNumber) - $available available of $($sku.PrepaidUnits.Enabled) total"
}

# Assign Exchange Online Plan 1 (EXCHANGESTANDARD) - cheapest option for mailbox access
$exoPlan = $skus | Where-Object { $_.SkuPartNumber -eq "EXCHANGESTANDARD" }
if ($exoPlan) {
    $availableCount = $exoPlan.PrepaidUnits.Enabled - $exoPlan.ConsumedUnits
    if ($availableCount -gt 0) {
        Set-MgUserLicense -UserId $lesley.Id -AddLicenses @(@{SkuId = $exoPlan.SkuId}) -RemoveLicenses @()
        Write-Output "[OK] Assigned Exchange Online Plan 1 ($availableCount were available)"
    } else {
        Write-Output "[WARNING] No Exchange Online Plan 1 licenses available, trying Business Standard..."
        $bizStd = $skus | Where-Object { $_.SkuPartNumber -eq "O365_BUSINESS_PREMIUM" }
        if ($bizStd) {
            $availableCount = $bizStd.PrepaidUnits.Enabled - $bizStd.ConsumedUnits
            if ($availableCount -gt 0) {
                Set-MgUserLicense -UserId $lesley.Id -AddLicenses @(@{SkuId = $bizStd.SkuId}) -RemoveLicenses @()
                Write-Output "[OK] Assigned M365 Business Standard ($availableCount were available)"
            } else {
                Write-Output "[ERROR] No available licenses of either type - assign manually"
            }
        }
    }
} else {
    Write-Output "[WARNING] EXCHANGESTANDARD SKU not found, trying Business Standard..."
    $bizStd = $skus | Where-Object { $_.SkuPartNumber -eq "O365_BUSINESS_PREMIUM" }
    if ($bizStd) {
        $availableCount = $bizStd.PrepaidUnits.Enabled - $bizStd.ConsumedUnits
        if ($availableCount -gt 0) {
            Set-MgUserLicense -UserId $lesley.Id -AddLicenses @(@{SkuId = $bizStd.SkuId}) -RemoveLicenses @()
            Write-Output "[OK] Assigned M365 Business Standard ($availableCount were available)"
        } else {
            Write-Output "[ERROR] No available licenses - assign manually"
        }
    }
}

# --- STEP 4: Connect to Exchange Online ---
Write-Output "`n[STEP 4] Connecting to Exchange Online..."
Import-Module ExchangeOnlineManagement
Connect-ExchangeOnline -UserPrincipalName "sysadmin@bgbuildersllc.com" -ShowBanner:$false
Write-Output "[OK] Connected to Exchange Online"

# --- STEP 5: Add Shelly as delegate ---
Write-Output "`n[STEP 5] Adding Shelly as delegate on Lesley's mailbox..."
Add-MailboxPermission -Identity $lesleyUPN -User $shellyUPN -AccessRights FullAccess -AutoMapping $true
Write-Output "[OK] Shelly granted FullAccess (auto-mapped)"

Add-RecipientPermission -Identity $lesleyUPN -Trustee $shellyUPN -AccessRights SendAs -Confirm:$false
Write-Output "[OK] Shelly granted SendAs"

# --- STEP 6: Enable litigation hold ---
Write-Output "`n[STEP 6] Enabling litigation hold (prevent email deletion)..."
Set-Mailbox -Identity $lesleyUPN -LitigationHoldEnabled $true -LitigationHoldDuration Unlimited
Write-Output "[OK] Litigation hold enabled - emails cannot be permanently deleted"

# --- STEP 7: Verify ---
Write-Output "`n[STEP 7] Verifying permissions..."
$perms = Get-MailboxPermission -Identity $lesleyUPN | Where-Object { $_.User -notlike "NT AUTHORITY*" -and $_.User -notlike "S-1-*" }
Write-Output "Current mailbox permissions:"
foreach ($p in $perms) {
    Write-Output "  $($p.User) - $($p.AccessRights -join ', ')"
}

# --- DONE ---
Write-Output "`n========================================="
Write-Output " COMPLETE"
Write-Output " $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
Write-Output "========================================="
Write-Output ""
Write-Output "Summary:"
Write-Output "  [OK] Lesley sign-in re-enabled"
Write-Output "  [OK] License reassigned"
Write-Output "  [OK] Shelly has FullAccess + SendAs on Lesley's mailbox"
Write-Output "  [OK] Litigation hold enabled - no email can be permanently deleted"
Write-Output "  [INFO] Barry still has access from termination script"

Disconnect-ExchangeOnline -Confirm:$false
Disconnect-MgGraph
