# Backup SQL Server database SolutionErp.
# Lập lịch qua Task Scheduler: daily 2:00 AM.
#
# Usage:
#   .\scripts\backup-sql.ps1 -Server "." -Database "SolutionErp" -BackupDir "C:\Backups\SolutionErp"
#
# Retention: giữ 30 ngày gần nhất (dọn file cũ hơn 30d).

param(
    [string]$Server = ".",
    [string]$Database = "SolutionErp",
    # [S168 K8 B0] Default C:\ — VPS prod KHONG co o D (do that: mkdir D:\ fail
    # "Cannot find drive"); D:\ cu la gia dinh chua tung chay tren may nay.
    [string]$BackupDir = "C:\Backups\SolutionErp",
    [int]$RetentionDays = 30
)

$ErrorActionPreference = 'Stop'

if (-not (Test-Path $BackupDir)) {
    New-Item -ItemType Directory -Force -Path $BackupDir | Out-Null
}

$timestamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$backupFile = Join-Path $BackupDir "${Database}_${timestamp}.bak"

Write-Host "Backup $Database -> $backupFile"

$sql = @"
BACKUP DATABASE [$Database]
TO DISK = N'$backupFile'
WITH
    INIT,
    COMPRESSION,
    CHECKSUM,
    NAME = N'$Database-Full-$timestamp',
    DESCRIPTION = N'Daily full backup';
"@

sqlcmd -S $Server -Q $sql -b
if ($LASTEXITCODE -ne 0) {
    throw "Backup FAIL (exit code $LASTEXITCODE)"
}

$fileSize = [math]::Round((Get-Item $backupFile).Length / 1MB, 2)
Write-Host "  Size: ${fileSize} MB"

# Retention: xoa file cu hon X ngay
Write-Host "Cleanup old backups (>$RetentionDays days)"
$cutoff = (Get-Date).AddDays(-$RetentionDays)
$oldFiles = Get-ChildItem -Path $BackupDir -Filter "*.bak" | Where-Object { $_.LastWriteTime -lt $cutoff }
foreach ($f in $oldFiles) {
    Write-Host "  Remove $($f.Name)"
    Remove-Item $f.FullName -Force
}

Write-Host "`nBackup SUCCESS" -ForegroundColor Green
