name: Build Release

on:
  push:
    tags:
      - 'v*'

jobs:
  build-windows:
    runs-on: windows-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Build portable distribution
        shell: pwsh
        run: |
          .\build-dist.ps1 -Version "${{ gitea.ref_name }}"

      - name: Upload build artifact
        uses: actions/upload-artifact@v3
        with:
          name: LedGrab-${{ gitea.ref_name }}-win-x64
          path: build/LedGrab-*.zip
          retention-days: 90

      - name: Create Gitea release
        shell: pwsh
        env:
          GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
        run: |
          $tag = "${{ gitea.ref_name }}"
          $zipFile = Get-ChildItem "build\LedGrab-*.zip" | Select-Object -First 1
          if (-not $zipFile) { throw "ZIP not found" }

          $baseUrl = "${{ gitea.server_url }}/api/v1/repos/${{ gitea.repository }}"
          $headers = @{
            "Authorization" = "token $env:GITEA_TOKEN"
            "Content-Type"  = "application/json"
          }

          # Create release
          $body = @{
            tag_name   = $tag
            name       = "LedGrab $tag"
            body       = "Portable Windows build — unzip, run ``LedGrab.bat``, open http://localhost:8080"
            draft      = $false
            prerelease = ($tag -match '(alpha|beta|rc)')
          } | ConvertTo-Json

          $release = Invoke-RestMethod -Method Post `
            -Uri "$baseUrl/releases" `
            -Headers $headers -Body $body

          Write-Host "Created release: $($release.html_url)"

          # Upload ZIP asset
          $uploadHeaders = @{
            "Authorization" = "token $env:GITEA_TOKEN"
          }
          $uploadUrl = "$baseUrl/releases/$($release.id)/assets?name=$($zipFile.Name)"
          Invoke-RestMethod -Method Post -Uri $uploadUrl `
            -Headers $uploadHeaders `
            -ContentType "application/octet-stream" `
            -InFile $zipFile.FullName

          Write-Host "Uploaded: $($zipFile.Name)"
