<#
.SYNOPSIS
  Erstellt ein neues GitHub-Issue und fügt es zum Project Board hinzu.
.DESCRIPTION
  Legt ein Issue an, fügt es zum Project Board hinzu, setzt den Board-Status
  und den Order-Wert.
  - Status "Todo" (Standard): Order = niedrigster Todo-Wert minus 1 → wird als nächstes Ticket eingereiht.
  - Status "Backlog": Order = höchster nicht-Done-Wert plus 10 → wird ans Ende gestellt.
.PARAMETER Title
  Titel des neuen Issues.
.PARAMETER Body
  Body-Text des Issues (Markdown). Optional, Default: leer.
.PARAMETER Labels
  Komma-separierte Labels (z.B. "migration,crm,enhancement"). Muss mindestens
  ein Type-Label enthalten: migration, tech-decision oder infrastructure.
.PARAMETER Status
  Board-Status des neuen Tickets: "Todo" (Standard) oder "Backlog".
#>
param(
    [Parameter(Mandatory)][string]$Title,
    [string]$Body = "",
    [Parameter(Mandatory)][string]$Labels,
    [ValidateSet("Todo", "Backlog")]
    [string]$Status = "Todo"
)

$repo           = "jreinemann-euris/krisenvorrat"
$projectId      = "PVT_kwHOCFqiJ84BXk9U"
$orderFieldId   = "PVTF_lAHOCFqiJ84BXk9UzhSw4jo"
$statusFieldId  = "PVTSSF_lAHOCFqiJ84BXk9UzhSw4es"
$statusOptionMap = @{
    "Todo"    = "f75ad846"
    "Backlog" = "4ce6ee37"
}

# --- 1. Type-Label validieren ---
$labelList = $Labels -split ',' | ForEach-Object { $_.Trim() }
$validTypes = @("migration","tech-decision","infrastructure","block-planning","feature","refactoring","planning","test")
$hasType = ($labelList | Where-Object { $validTypes -contains $_ }).Count -gt 0
if (-not $hasType) {
    Write-Error "Mindestens ein Type-Label erforderlich: $($validTypes -join ', ')"
    exit 1
}

# --- 2. Issue anlegen ---
$createArgs = @("issue", "create", "--repo", $repo, "--title", $Title, "--label", $Labels)
if ($Body) {
    $createArgs += "--body"
    $createArgs += $Body
}
$issueUrl = & gh @createArgs 2>&1
if ($LASTEXITCODE -ne 0) {
    Write-Error "Fehler beim Anlegen des Issues: $issueUrl"
    exit 1
}

$issueNumber = ($issueUrl -split '/')[-1]

# --- 3. Zum Board hinzufügen ---
$addResult = gh project item-add 2 --owner jreinemann-euris --url $issueUrl --format json 2>&1
if ($LASTEXITCODE -ne 0) {
    Write-Error "Fehler beim Hinzufügen zum Board: $addResult"
    exit 1
}
$itemId = ($addResult | ConvertFrom-Json).id

# --- 4. Order-Wert ermitteln ---
$raw = gh project item-list 2 --owner jreinemann-euris --format json --limit 200 | ConvertFrom-Json
$otherItems = $raw.items | Where-Object { $_.status -ne "Done" -and $_.id -ne $itemId }

if ($Status -eq "Todo") {
    # Als nächstes Ticket: niedrigster bestehender Wert minus 1
    $refOrder = $otherItems |
        ForEach-Object { [double]$_.order } |
        Where-Object { $_ -gt 0 } |
        Measure-Object -Minimum |
        Select-Object -ExpandProperty Minimum
    if ($null -eq $refOrder) { $refOrder = 10 }
    $newOrder = $refOrder - 1
} else {
    # Backlog: ans Ende stellen (höchster bestehender Wert plus 10)
    $refOrder = $otherItems |
        ForEach-Object { [double]$_.order } |
        Where-Object { $_ -gt 0 } |
        Measure-Object -Maximum |
        Select-Object -ExpandProperty Maximum
    if ($null -eq $refOrder) { $refOrder = 0 }
    $newOrder = $refOrder + 10
}

# --- 5. Order setzen ---
gh project item-edit --project-id $projectId --id $itemId --field-id $orderFieldId --number $newOrder 2>&1 | Out-Null
if ($LASTEXITCODE -ne 0) {
    Write-Error "Fehler beim Setzen des Order-Werts."
    exit 1
}

# --- 6. Board-Status setzen ---
$optionId = $statusOptionMap[$Status]
gh project item-edit --project-id $projectId --id $itemId --field-id $statusFieldId --single-select-option-id $optionId 2>&1 | Out-Null
if ($LASTEXITCODE -ne 0) {
    Write-Error "Fehler beim Setzen des Board-Status."
    exit 1
}

Write-Host "#$issueNumber $Title (Status: $Status, Order: $newOrder)"
