# backup-db.ps1
# Backs up the TestDataDB SQLite database with 7-day retention.
# Intended to run as a scheduled task via install-backup-task.ps1.

$ErrorActionPreference = 'Stop'

$SourceDb   = 'C:\Shares\testdatadb\database\testdata.db'
$BackupDir  = 'C:\Shares\testdatadb\backups'
$LogFile    = 'C:\Shares\testdatadb\logs\backup.log'
$Retention  = 7

function Write-Log {
    param([string]$Message)
    $timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
    $entry = "[$timestamp] $Message"
    Add-Content -Path $LogFile -Value $entry
    Write-Host $entry
}

# Ensure directories exist
foreach ($dir in @($BackupDir, (Split-Path $LogFile -Parent))) {
    if (-not (Test-Path $dir)) {
        New-Item -ItemType Directory -Path $dir -Force | Out-Null
    }
}

# Verify source database exists
if (-not (Test-Path $SourceDb)) {
    Write-Log "[ERROR] Source database not found: $SourceDb"
    exit 1
}

# Create dated backup
$datestamp  = Get-Date -Format 'yyyy-MM-dd'
$backupFile = Join-Path $BackupDir "testdata-$datestamp.db"

try {
    Copy-Item -Path $SourceDb -Destination $backupFile -Force
    $sizeKb = [math]::Round((Get-Item $backupFile).Length / 1024, 1)
    Write-Log "[OK] Backup created: $backupFile ($sizeKb KB)"
} catch {
    Write-Log "[ERROR] Backup failed: $_"
    exit 1
}

# Prune old backups beyond retention period
$cutoff = (Get-Date).AddDays(-$Retention)
$oldBackups = Get-ChildItem -Path $BackupDir -Filter 'testdata-*.db' |
    Where-Object { $_.LastWriteTime -lt $cutoff }

foreach ($old in $oldBackups) {
    try {
        Remove-Item -Path $old.FullName -Force
        Write-Log "[OK] Deleted old backup: $($old.Name)"
    } catch {
        Write-Log "[WARNING] Could not delete old backup: $($old.Name) - $_"
    }
}

$remaining = (Get-ChildItem -Path $BackupDir -Filter 'testdata-*.db').Count
Write-Log "[INFO] Backup complete. $remaining backup(s) on disk."
