# BG Builders - Lesley Roth 72-Hour Mail Activity Report
# Pulls sent mail (message trace) and deleted items (mailbox audit log)
# Date: 2026-03-09

$ErrorActionPreference = "Stop"
$lesleyUPN = "lesley@bgbuildersllc.com"
$startDate = (Get-Date).AddHours(-72)
$endDate = Get-Date
$reportPath = "D:\ClaudeTools\scripts\bgb-lesley-mail-report-$(Get-Date -Format 'yyyyMMdd').txt"

Write-Output "========================================="
Write-Output " BG Builders - Lesley Roth Mail Report"
Write-Output " 72-Hour Window: $($startDate.ToString('yyyy-MM-dd HH:mm')) to $($endDate.ToString('yyyy-MM-dd HH:mm'))"
Write-Output "========================================="

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

# Start building report
$report = @()
$report += "========================================="
$report += " LESLEY ROTH - 72-HOUR MAIL ACTIVITY REPORT"
$report += " Generated: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
$report += " Window: $($startDate.ToString('yyyy-MM-dd HH:mm')) to $($endDate.ToString('yyyy-MM-dd HH:mm'))"
$report += "========================================="

# --- SENT MAIL (Message Trace) ---
Write-Output "`n[STEP 2] Pulling sent mail via message trace..."
$sentMessages = Get-MessageTraceV2 -SenderAddress $lesleyUPN -StartDate $startDate -EndDate $endDate 
$report += ""
$report += "=========================================`n SENT MESSAGES ($($sentMessages.Count) total)`n========================================="

if ($sentMessages.Count -gt 0) {
    $sentMessages | Sort-Object Received -Descending | ForEach-Object {
        $report += ""
        $report += "  Date:    $($_.Received.ToString('yyyy-MM-dd HH:mm:ss'))"
        $report += "  To:      $($_.RecipientAddress)"
        $report += "  Subject: $($_.Subject)"
        $report += "  Status:  $($_.Status)"
        $report += "  Size:    $([math]::Round($_.Size / 1KB, 1)) KB"
        $report += "  MsgID:   $($_.MessageId)"
        $report += "  ---"
    }
} else {
    $report += "  [NONE] No sent messages in the last 72 hours"
}
Write-Output "[OK] Found $($sentMessages.Count) sent messages"

# --- RECEIVED MAIL (Message Trace) ---
Write-Output "`n[STEP 3] Pulling received mail via message trace..."
$receivedMessages = Get-MessageTraceV2 -RecipientAddress $lesleyUPN -StartDate $startDate -EndDate $endDate 
$report += ""
$report += "=========================================`n RECEIVED MESSAGES ($($receivedMessages.Count) total)`n========================================="

if ($receivedMessages.Count -gt 0) {
    $receivedMessages | Sort-Object Received -Descending | ForEach-Object {
        $report += ""
        $report += "  Date:    $($_.Received.ToString('yyyy-MM-dd HH:mm:ss'))"
        $report += "  From:    $($_.SenderAddress)"
        $report += "  Subject: $($_.Subject)"
        $report += "  Status:  $($_.Status)"
        $report += "  ---"
    }
} else {
    $report += "  [NONE] No received messages in the last 72 hours"
}
Write-Output "[OK] Found $($receivedMessages.Count) received messages"

# --- DELETED ITEMS (Mailbox Audit Log) ---
Write-Output "`n[STEP 4] Pulling deleted items via mailbox audit log..."

# Use Search-UnifiedAuditLog (Search-MailboxAuditLog deprecated Jan 2026)
$deleteOps = "SoftDelete","HardDelete","MoveToDeletedItems"
$deletedItems = Search-UnifiedAuditLog -UserIds $lesleyUPN -Operations ($deleteOps -join ",") -StartDate $startDate -EndDate $endDate -ResultSize 5000

$report += ""
$report += "=========================================`n DELETED ITEMS ($($deletedItems.Count) total)`n========================================="

if ($deletedItems.Count -gt 0) {
    $deletedItems | Sort-Object CreationDate -Descending | ForEach-Object {
        $auditData = $_.AuditData | ConvertFrom-Json
        $report += ""
        $report += "  Date:      $($_.CreationDate)"
        $report += "  Operation: $($_.Operations)"
        $report += "  User:      $($_.UserIds)"
        $report += "  Subject:   $($auditData.AffectedItems.Subject -join '; ')"
        $report += "  Folder:    $($auditData.Folder.Path)"
        $report += "  Client:    $($auditData.ClientInfoString)"
        $report += "  ---"
    }
} else {
    $report += "  [NONE] No deleted items in the last 72 hours"
}
Write-Output "[OK] Found $($deletedItems.Count) deleted items"

# --- INBOX RULES (check for forwarding/auto-delete) ---
Write-Output "`n[STEP 5] Checking inbox rules..."
$rules = Get-InboxRule -Mailbox $lesleyUPN 2>$null

$report += ""
$report += "=========================================`n INBOX RULES`n========================================="

if ($rules) {
    foreach ($rule in $rules) {
        $report += ""
        $report += "  Name:       $($rule.Name)"
        $report += "  Enabled:    $($rule.Enabled)"
        $report += "  Priority:   $($rule.Priority)"
        if ($rule.ForwardTo) { $report += "  ForwardTo:  $($rule.ForwardTo -join '; ')" }
        if ($rule.RedirectTo) { $report += "  RedirectTo: $($rule.RedirectTo -join '; ')" }
        if ($rule.DeleteMessage) { $report += "  [WARNING] Auto-delete enabled" }
        $report += "  ---"
    }
} else {
    $report += "  [NONE] No inbox rules configured"
}
Write-Output "[OK] Rules checked"

# --- FORWARDING CONFIG ---
Write-Output "`n[STEP 6] Checking forwarding configuration..."
$mbx = Get-Mailbox -Identity $lesleyUPN | Select-Object ForwardingAddress,ForwardingSmtpAddress,DeliverToMailboxAndForward

$report += ""
$report += "=========================================`n FORWARDING CONFIGURATION`n========================================="
$report += "  ForwardingAddress:         $($mbx.ForwardingAddress)"
$report += "  ForwardingSmtpAddress:     $($mbx.ForwardingSmtpAddress)"
$report += "  DeliverToMailboxAndForward: $($mbx.DeliverToMailboxAndForward)"

if ($mbx.ForwardingAddress -or $mbx.ForwardingSmtpAddress) {
    $report += "  [WARNING] Active forwarding detected!"
} else {
    $report += "  [OK] No forwarding configured"
}

# --- Write report to file ---
$report | Out-File -FilePath $reportPath -Encoding UTF8
Write-Output "`n========================================="
Write-Output " REPORT SAVED"
Write-Output " $reportPath"
Write-Output "========================================="

# Also output to console
Write-Output "`n--- REPORT CONTENTS ---"
$report | ForEach-Object { Write-Output $_ }

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