[CmdletBinding()]
param(
    [string]$ScriptPath = "C:\FlutterProjetos\bulo_backend\tools\backup_mysql_bulo.ps1",
    [string]$DailyTime = "03:00",
    [int]$BinlogMinutes = 5,
    [string]$OffsiteRoot = "C:\Users\Igor Loffhagen\OneDrive\BuloBackups"
)

$ErrorActionPreference = "Stop"

if (-not (Test-Path -LiteralPath $ScriptPath)) {
    throw "Script de backup nao encontrado: $ScriptPath"
}

$fullTask = "Bulo MySQL Backup Completo Diario"
$binlogTask = "Bulo MySQL Backup Binlog 5min"

$powershell = "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe"
$fullAction = "`"$powershell`" -WindowStyle Hidden -NoProfile -ExecutionPolicy Bypass -File `"$ScriptPath`" -Mode full -OffsiteRoot `"$OffsiteRoot`""
$binlogAction = "`"$powershell`" -WindowStyle Hidden -NoProfile -ExecutionPolicy Bypass -File `"$ScriptPath`" -Mode binlog -OffsiteRoot `"$OffsiteRoot`""

function New-BackupTask([string]$Name, [string]$Action, [string[]]$ScheduleArgs) {
    & schtasks /Create /TN $Name /TR $Action @ScheduleArgs /F | Out-Host
    if ($LASTEXITCODE -ne 0) {
        throw "Falha ao criar tarefa agendada: $Name"
    }
}

New-BackupTask $fullTask $fullAction @("/SC", "DAILY", "/ST", $DailyTime)
New-BackupTask $binlogTask $binlogAction @("/SC", "MINUTE", "/MO", "$BinlogMinutes")

Write-Output "Tarefas criadas:"
Write-Output "- ${fullTask}: todo dia as $DailyTime"
Write-Output "- ${binlogTask}: a cada $BinlogMinutes minutos"
Write-Output "Opcional: defina BULO_BACKUP_OFFSITE para copiar tambem para OneDrive/Google Drive/outro disco."
