# =============================================================================
# Deploy Script — myEventPostMortem (Laravel)
# Windows Server 2019
#
# Dipanggil oleh public/webhook.php apabila Gitea push event diterima.
# Pastikan user yang menjalankan IIS/PHP ada akses ke git, composer, npm, php.
# =============================================================================

$AppRoot = Split-Path -Parent $PSScriptRoot
$ErrorActionPreference = "Stop"

function Write-Log {
    param([string]$Message)
    $ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    Write-Output "[$ts] $Message"
}

function Invoke-Step {
    param([string]$Label, [scriptblock]$Action)
    Write-Log ">>> $Label"
    & $Action
    if ($LASTEXITCODE -ne 0) {
        throw "$Label gagal dengan exit code $LASTEXITCODE"
    }
}

# ── Masuk ke direktori aplikasi ──────────────────────────────────────────────
Set-Location $AppRoot
Write-Log "=== Deployment Bermula ==="
Write-Log "App Root : $AppRoot"
Write-Log "User     : $env:USERNAME"
Write-Log "Masa     : $(Get-Date)"

# ── Git pull ─────────────────────────────────────────────────────────────────
Invoke-Step "Git pull" {
    git pull origin master
}

# ── Composer install ─────────────────────────────────────────────────────────
Invoke-Step "Composer install" {
    composer install --no-dev --optimize-autoloader --no-interaction --no-progress
}

# ── NPM install & build ──────────────────────────────────────────────────────
Invoke-Step "NPM install" {
    npm ci --prefer-offline
}

Invoke-Step "NPM build" {
    npm run build
}

# ── Laravel: cache config & migrate ─────────────────────────────────────────
Invoke-Step "Artisan down (maintenance mode)" {
    php artisan down --retry=10
}

try {
    Invoke-Step "Database migrate" {
        php artisan migrate --force
    }

    Invoke-Step "Optimize Laravel" {
        php artisan optimize
    }

    Invoke-Step "Queue restart" {
        php artisan queue:restart
    }
}
finally {
    # Pastikan aplikasi dibuka semula walaupun ada ralat
    Write-Log ">>> Artisan up"
    php artisan up
}

Write-Log "=== Deployment Berjaya ==="
