name: Build/Release

permissions:
  contents: write

on:
  push:
    branches:
      - main

jobs:
  release:
    runs-on: windows-latest

    steps:
      - name: Check out repository
        uses: actions/checkout@v4

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

      - name: Install dependencies
        run: npm ci

      - name: Calculate release version
        id: version
        shell: pwsh
        env:
          GH_TOKEN: ${{ secrets.GH_TOKEN != '' && secrets.GH_TOKEN || secrets.GITHUB_TOKEN }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          node scripts/ci/update-version.js $env:GITHUB_OUTPUT
          if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

      - name: Build/release Electron app
        uses: samuelmeuli/action-electron-builder@v1
        with:
          github_token: ${{ secrets.GH_TOKEN != '' && secrets.GH_TOKEN || secrets.GITHUB_TOKEN }}
          release: false
          args: --win --x64 --publish never
        env:
          GH_TOKEN: ${{ secrets.GH_TOKEN != '' && secrets.GH_TOKEN || secrets.GITHUB_TOKEN }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Create GitHub release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: v${{ steps.version.outputs.tag }}
          name: ${{ steps.version.outputs.tag }}
          prerelease: false
          draft: false
          files: |
            dist/*Setup*.exe
            dist/*Setup*.exe.blockmap
        env:
          GITHUB_TOKEN: ${{ secrets.GH_TOKEN != '' && secrets.GH_TOKEN || secrets.GITHUB_TOKEN }}

      - name: Upload installer artifact
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: windows-installer-${{ steps.version.outputs.tag }}
          path: |
            dist/*Setup*.exe
            dist/*Setup*.exe.blockmap
