# Get Exchange Online logs for notifications@dataforth.com
# This script retrieves message traces and mailbox audit logs

Write-Host "[OK] Checking Exchange Online connection..." -ForegroundColor Green

# Check if connected to Exchange Online
$Session = Get-PSSession | Where-Object { $_.ConfigurationName -eq "Microsoft.Exchange" -and $_.State -eq "Opened" }

if (-not $Session) {
    Write-Host "[WARNING] Not connected to Exchange Online" -ForegroundColor Yellow
    Write-Host "          Connecting now..." -ForegroundColor Yellow
    Write-Host ""

    try {
        Connect-ExchangeOnline -UserPrincipalName sysadmin@dataforth.com -ShowBanner:$false
        Write-Host "[OK] Connected to Exchange Online" -ForegroundColor Green
    } catch {
        Write-Host "[ERROR] Failed to connect to Exchange Online" -ForegroundColor Red
        Write-Host "        Error: $($_.Exception.Message)" -ForegroundColor Red
        exit 1
    }
}

Write-Host ""
Write-Host "================================================================"
Write-Host "1. Checking SMTP AUTH status"
Write-Host "================================================================"

$CASMailbox = Get-CASMailbox -Identity notifications@dataforth.com
Write-Host "[OK] SMTP AUTH Status:"
Write-Host "    SmtpClientAuthenticationDisabled: $($CASMailbox.SmtpClientAuthenticationDisabled)"

if ($CASMailbox.SmtpClientAuthenticationDisabled -eq $true) {
    Write-Host "[ERROR] SMTP AUTH is DISABLED for this mailbox!" -ForegroundColor Red
    Write-Host "        To enable: Set-CASMailbox -Identity notifications@dataforth.com -SmtpClientAuthenticationDisabled `$false" -ForegroundColor Yellow
} else {
    Write-Host "[OK] SMTP AUTH is enabled" -ForegroundColor Green
}

Write-Host ""
Write-Host "================================================================"
Write-Host "2. Checking message trace (last 7 days)"
Write-Host "================================================================"

$StartDate = (Get-Date).AddDays(-7)
$EndDate = Get-Date

Write-Host "[OK] Searching for messages from notifications@dataforth.com..."

$Messages = Get-MessageTrace -SenderAddress notifications@dataforth.com -StartDate $StartDate -EndDate $EndDate

if ($Messages) {
    Write-Host "[OK] Found $($Messages.Count) messages sent in the last 7 days" -ForegroundColor Green
    Write-Host ""

    $Messages | Select-Object -First 10 | Format-Table Received, RecipientAddress, Subject, Status, Size -AutoSize

    $FailedMessages = $Messages | Where-Object { $_.Status -ne "Delivered" }
    if ($FailedMessages) {
        Write-Host ""
        Write-Host "[WARNING] Found $($FailedMessages.Count) failed/pending messages:" -ForegroundColor Yellow
        $FailedMessages | Format-Table Received, RecipientAddress, Subject, Status -AutoSize
    }
} else {
    Write-Host "[WARNING] No messages found in the last 7 days" -ForegroundColor Yellow
    Write-Host "          This suggests emails are not reaching Exchange Online" -ForegroundColor Yellow
}

Write-Host ""
Write-Host "================================================================"
Write-Host "3. Checking mailbox audit logs"
Write-Host "================================================================"

Write-Host "[OK] Checking for authentication events..."

$AuditLogs = Search-MailboxAuditLog -Identity notifications@dataforth.com -StartDate $StartDate -EndDate $EndDate -ShowDetails

if ($AuditLogs) {
    Write-Host "[OK] Found $($AuditLogs.Count) audit events" -ForegroundColor Green
    $AuditLogs | Select-Object -First 10 | Format-Table LastAccessed, Operation, LogonType, ClientIPAddress -AutoSize
} else {
    Write-Host "[OK] No mailbox audit events found" -ForegroundColor Green
}

Write-Host ""
Write-Host "================================================================"
Write-Host "4. Checking for failed authentication attempts (Unified Audit Log)"
Write-Host "================================================================"

Write-Host "[OK] Searching for failed logins..."

$AuditRecords = Search-UnifiedAuditLog -UserIds notifications@dataforth.com -StartDate $StartDate -EndDate $EndDate -Operations UserLoginFailed,MailboxLogin -ResultSize 100

if ($AuditRecords) {
    Write-Host "[WARNING] Found $($AuditRecords.Count) authentication events" -ForegroundColor Yellow
    Write-Host ""

    foreach ($Record in $AuditRecords | Select-Object -First 5) {
        $AuditData = $Record.AuditData | ConvertFrom-Json
        Write-Host "  [EVENT] $($Record.CreationDate)"
        Write-Host "    Operation: $($Record.Operations)"
        Write-Host "    Client IP: $($AuditData.ClientIP)"
        Write-Host "    Result: $($AuditData.ResultStatus)"
        if ($AuditData.LogonError) {
            Write-Host "    Error: $($AuditData.LogonError)" -ForegroundColor Red
        }
        Write-Host ""
    }
} else {
    Write-Host "[OK] No failed authentication attempts found" -ForegroundColor Green
}

Write-Host ""
Write-Host "================================================================"
Write-Host "SUMMARY"
Write-Host "================================================================"
Write-Host "Review the logs above to identify the issue."
Write-Host ""
Write-Host "Common issues:"
Write-Host "  - SMTP AUTH disabled (check section 1)"
Write-Host "  - Wrong credentials (check section 4 for failed logins)"
Write-Host "  - No messages reaching Exchange (check section 2)"
Write-Host "  - Firewall blocking connection"
Write-Host "  - App needs app-specific password (if MFA enabled)"
