tests/fixtures/e2e/Update-DynamicFixtureDates.ps1

<#
.SYNOPSIS
    Refresh the Date header of dynamically-dated e2e .eml fixtures.

.DESCRIPTION
    Some e2e fixtures must always fall in a specific recency band (e.g. 6-12 months
    old) no matter when the pipeline runs. Those fixtures declare their intended age
    via an 'X-LeadForge-Dynamic-Age-Months' header. This script rewrites each such
    fixture's 'Date' header to (now - age months) so the recency bands never drift as
    real time passes.

    Fixtures without the dynamic-age header (e.g. the fixed-scenario emails) are left
    untouched. Run this immediately before executing the e2e pipeline.

.PARAMETER Path
    Folder containing the .eml fixtures. Defaults to this script's folder.

.EXAMPLE
    ./Update-DynamicFixtureDates.ps1
#>

[CmdletBinding()]
param(
    [string]$Path = $PSScriptRoot
)

$ageHeader = 'X-LeadForge-Dynamic-Age-Months'
$updated = @()

foreach ($file in Get-ChildItem -Path $Path -Filter '*.eml') {
    $lines = @(Get-Content -LiteralPath $file.FullName)

    $ageLine = $lines | Where-Object { $_ -match "^${ageHeader}:\s*(\d+)\s*$" } | Select-Object -First 1
    if (-not $ageLine) { continue }

    [void]($ageLine -match "^${ageHeader}:\s*(\d+)\s*$")
    $ageMonths = [int]$Matches[1]

    # Compute the target date relative to now and format it as an RFC 2822 Date.
    # InvariantCulture guarantees the canonical 3-letter month (e.g. 'Sep', not the
    # .NET en-US 'Sept'); strip the colon from the offset (+01:00 -> +0100).
    $target = [System.DateTimeOffset]::new((Get-Date).AddMonths(-$ageMonths))
    $rfc = $target.ToString('ddd, dd MMM yyyy HH:mm:ss zzz', [System.Globalization.CultureInfo]::InvariantCulture)
    $rfc = $rfc -replace '([+-]\d{2}):(\d{2})$', '$1$2'

    $inHeaders = $true
    $replaced = $false
    $newLines = foreach ($line in $lines) {
        if ($inHeaders -and $line -eq '') {
            $inHeaders = $false
            $line
        }
        elseif ($inHeaders -and -not $replaced -and $line -match '^Date:\s') {
            $replaced = $true
            "Date: $rfc"
        }
        else {
            $line
        }
    }

    Set-Content -LiteralPath $file.FullName -Value $newLines -Encoding utf8
    $updated += [pscustomobject]@{ File = $file.Name; AgeMonths = $ageMonths; Date = $rfc }
}

if ($updated) {
    Write-Host 'Refreshed dynamic fixture dates:' -ForegroundColor Cyan
    $updated | ForEach-Object { Write-Host (' {0,-34} -> {1} ({2} months old)' -f $_.File, $_.Date, $_.AgeMonths) }
}
else {
    Write-Host "No dynamically-dated fixtures found in $Path" -ForegroundColor Yellow
}

return $updated