name: Build and Release

on:
  push:
    branches:
      - main

jobs:
  build:
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: macos-latest
            platform: mac
          - os: windows-latest
            platform: win

    runs-on: ${{ matrix.os }}

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

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

      - name: Install Yarn
        run: npm install -g yarn

      - name: Install dependencies
        run: yarn install

      - name: Install ImageMagick (Windows)
        if: matrix.platform == 'win'
        run: choco install imagemagick -y

      - name: Build web (client + server)
        run: npm run build

      - name: Build desktop
        run: npm run desktop:build

      - name: Build desktop distribution
        working-directory: desktop
        run: npm run dist:${{ matrix.platform }}

      - name: Collect distributable files
        shell: bash
        run: |
          mkdir -p dist-output
          cp desktop/release/*.dmg dist-output/ 2>/dev/null || true
          cp desktop/release/*.exe dist-output/ 2>/dev/null || true
          cp desktop/release/*.AppImage dist-output/ 2>/dev/null || true
          ls -la dist-output/

      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: desktop-${{ matrix.platform }}
          path: dist-output/*
          if-no-files-found: error

  release:
    needs: build
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Get Version from package.json
        id: get_version
        run: echo "version=$(node -p "require('./package.json').version")" >> $GITHUB_OUTPUT

      - name: Download all artifacts
        uses: actions/download-artifact@v4
        with:
          path: artifacts
          merge-multiple: true

      - name: List release files
        run: ls -la artifacts/

      - name: Create Release
        uses: softprops/action-gh-release@v2
        env:
          GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }}
        with:
          tag_name: v${{ steps.get_version.outputs.version }}
          name: "🎉 Release ${{ steps.get_version.outputs.version }} 🎉"
          draft: false
          prerelease: false
          files: artifacts/*
