param(
  [string]$BaseUrl = "http://localhost:3000",
  [string]$Username = "alice",
  [string]$Password = "alice123",
  [int]$JwtValidationRequests = 10000,
  [int]$JwtValidationVUs = 100,
  [int]$BulkVUs = 20,
  [int]$BulkRounds = 3,
  [int]$SmallVUs = 6,
  [int]$SmallIterationsPerVu = 12,
  [int]$SmallFileCount = 5,
  [int]$CrashDelaySeconds = 10,
  [int]$PauseBetweenRequestsMs = 0
)

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

function Require-Command {
  param([string]$Name)
  if (-not (Get-Command $Name -ErrorAction SilentlyContinue)) {
    throw "Required command '$Name' not found in PATH."
  }
}

Require-Command "k6"

$repoRoot = Split-Path -Parent $PSScriptRoot
$testDataRoot = Join-Path $repoRoot "testData"
$jwtScriptPath = Join-Path $PSScriptRoot "k6/jwt-validation.js"
$scriptPath = Join-Path $PSScriptRoot "k6/upload-and-crash.js"

if (-not (Test-Path $testDataRoot)) {
  throw "testData directory not found: $testDataRoot"
}

$fileList = Get-ChildItem -Path $testDataRoot -Recurse -File |
    ForEach-Object {
      $_.FullName.Replace("\", "/")
    }

if (-not $fileList -or $fileList.Count -eq 0) {
  throw "No files found in testData."
}

$env:BASE_URL = $BaseUrl
$env:USERNAME = $Username
$env:PASSWORD = $Password
$env:JWT_VALIDATION_REQUESTS = "$JwtValidationRequests"
$env:JWT_VALIDATION_VUS = "$JwtValidationVUs"
$env:BULK_VUS = "$BulkVUs"
$env:BULK_ROUNDS = "$BulkRounds"
$env:SMALL_VUS = "$SmallVUs"
$env:SMALL_ITERATIONS_PER_VU = "$SmallIterationsPerVu"
$env:SMALL_FILE_COUNT = "$SmallFileCount"
$env:CRASH_DELAY_SECONDS = "$CrashDelaySeconds"
$env:PAUSE_BETWEEN_REQUESTS_MS = "$PauseBetweenRequestsMs"
$env:K6_FILE_LIST_JSON = ($fileList | ConvertTo-Json -Compress)

Write-Host "[k6] Files discovered: $($fileList.Count)"
Write-Host "[k6] Running JWT validation pre-test against $BaseUrl"

Push-Location $repoRoot
try {
  & k6 run $jwtScriptPath
  if ($LASTEXITCODE -ne 0) {
    throw "k6 JWT validation pre-test failed with exit code $LASTEXITCODE"
  }
  Write-Host "[k6] Running upload and crash scenario against $BaseUrl"
  & k6 run $scriptPath
  if ($LASTEXITCODE -ne 0) {
    throw "k6 upload-and-crash test failed with exit code $LASTEXITCODE"
  }
}
finally {
  Pop-Location
}
