<#
.SYNOPSIS
  Aggiorna il livello di notifica GitLab per un range di utenti
  e logga tutto in C:\Steamware\Logs\Gitlab\notificationLevelChange.log
#>

# importa configurazioni
. .\ApiGit\ApiGitResources\ApiScriptsConfig.ps1
. .\ApiGit\ApiGitResources\ApiScriptsFunctions.ps1

$GitlabUrl = "https://gitlab.steamware.net"
$PrivateToken = $tokenGitlab

# Range utenti da aggiornare (modificabile)
$StartId = 1
$EndId   = 50

# Livello notifiche da impostare (modificabile)
$NewLevel = "mention"   # altri valori: disabled, participating, watch, global, custom

# Percorso log
$LogDir  = "C:\Steamware\Logs\Gitlab"
$LogFile = Join-Path $LogDir "notificationLevelChange.log"

# Crea cartella log se non esiste
if (-not (Test-Path $LogDir)) {
    New-Item -Path $LogDir -ItemType Directory -Force | Out-Null
}

# Header base
$baseHeaders = @{
    "PRIVATE-TOKEN" = $PrivateToken
    "Content-Type"  = "application/json"
}

# Corpo JSON della richiesta
$body = @{ level = $NewLevel } | ConvertTo-Json

# Inizializza log
"INFO [$((Get-Date).ToString('o'))] Starting notification level update for IDs $StartId-$EndId (level=$NewLevel)" |
    Out-File -FilePath $LogFile -Encoding UTF8

# Ciclo utenti
for ($id = $StartId; $id -le $EndId; $id++) {

    $separator = "----- USER $id -----"
    $url = "$GitlabUrl/api/v4/notification_settings"

    # Clona headers e aggiunge Sudo per modificare altri utenti
    $headers = @{}
    foreach ($k in $baseHeaders.Keys) { $headers[$k] = $baseHeaders[$k] }
    $headers["Sudo"] = "$id"

    try {
        $response = Invoke-WebRequest `
            -Method PUT `
            -Uri $url `
            -Headers $headers `
            -Body $body `
            -ErrorAction Stop

        "$separator`nINFO [$((Get-Date).ToString('o'))] UPDATED id=$id level=$NewLevel status=$($response.StatusCode)" |
            Out-File -FilePath $LogFile -Encoding UTF8 -Append
    }
    catch {
        $msg = $_.Exception.Message -replace "`r?`n"," "
        "$separator`nERROR [$((Get-Date).ToString('o'))] FAILED id=$id message=$msg" |
            Out-File -FilePath $LogFile -Encoding UTF8 -Append
    }

    Start-Sleep -Milliseconds 150
}

"INFO [$((Get-Date).ToString('o'))] Completed." |
    Out-File -FilePath $LogFile -Encoding UTF8 -Append

Write-Host "Fatto. Log salvato in $LogFile"