# Cascades of Tucson -- Terminate Niel Castro (n.castro)
# Date: 2026-05-18
# Run on: CS-SERVER as a domain admin
# Run M365 steps separately via Graph / Exchange Online
#
# Reason: confirmed departed per updated HR roster (employees.xlsx, 2026-05-18)
# Account was created 2026-05-16 -- no M365 license was assigned, but account
# may have synced to Entra via Entra Connect. Block sign-in on both layers.
#
# Follows: docs/security/termination-procedures.md

$Sam = "n.castro"
$UPN = "n.castro@cascadestucson.com"
$Group = "SG-Caregivers"

Write-Host "=== AD: Disable $Sam ==="

$user = Get-ADUser -Filter "SamAccountName -eq '$Sam'" -ErrorAction SilentlyContinue
if (-not $user) {
    Write-Host "[ERROR] $Sam not found in AD -- nothing to do"
    exit 1
}

# Disable account
try {
    Disable-ADAccount -Identity $Sam
    Write-Host "[OK] $Sam disabled"
}
catch {
    Write-Host "[ERROR] Disable-ADAccount: $_"
}

# Remove from SG-Caregivers
$inGroup = Get-ADGroupMember -Identity $Group -ErrorAction SilentlyContinue |
           Where-Object { $_.SamAccountName -eq $Sam }

if ($inGroup) {
    try {
        Remove-ADGroupMember -Identity $Group -Members $Sam -Confirm:$false
        Write-Host "[OK] $Sam removed from $Group"
    }
    catch {
        Write-Host "[ERROR] Remove-ADGroupMember: $_"
    }
}
else {
    Write-Host "[SKIP] $Sam was not in $Group"
}

# Update description
try {
    Set-ADUser -Identity $Sam -Description "TERMINATED 2026-05-18"
    Write-Host "[OK] Description updated"
}
catch {
    Write-Host "[ERROR] Set-ADUser description: $_"
}

Write-Host ""
Write-Host "=== M365 steps (run separately in Exchange Online / Graph) ==="
Write-Host ""
Write-Host "1. Block sign-in:"
Write-Host "   Update-MgUser -UserId '$UPN' -AccountEnabled:`$false"
Write-Host ""
Write-Host "2. Revoke active sessions:"
Write-Host "   Invoke-MgInvalidateAllUserRefreshToken -UserId '$UPN'"
Write-Host "     -- or --"
Write-Host "   Revoke-MgUserSignInSession -UserId '$UPN'"
Write-Host ""
Write-Host "3. If mailbox exists -- check first:"
Write-Host "   Get-Mailbox -Identity '$UPN' -ErrorAction SilentlyContinue"
Write-Host "   If found:"
Write-Host "   Set-Mailbox -Identity '$UPN' -Type Shared"
Write-Host "   Set-Mailbox -Identity '$UPN' -HiddenFromAddressListsEnabled `$true"
Write-Host "   (License already unlicensed -- no license removal step needed)"
Write-Host ""
Write-Host "4. Force Entra Connect delta sync so the disable propagates to cloud:"
Write-Host "   Start-ADSyncSyncCycle -PolicyType Delta"
Write-Host ""
Write-Host "5. Log in docs/issues/log.md -- termination date 2026-05-18, performed by Howard"
