name: Release Binaries

on:
  push:
    branches:
      - main

permissions:
  id-token: write
  contents: write

env:
  NODE_VERSION: 20

jobs:
  prepare-release:
    runs-on: ubuntu-latest
    outputs:
      version: ${{ steps.get_version.outputs.version }}
      tag: ${{ steps.ensure_tag.outputs.tag }}
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}

      - name: Read version
        id: get_version
        run: |
          VERSION=$(node -p "require('./package.json').version")
          echo "version=$VERSION" >> "$GITHUB_OUTPUT"

      - name: Ensure git tag
        id: ensure_tag
        env:
          VERSION: ${{ steps.get_version.outputs.version }}
        run: |
          TAG="v${VERSION}"
          git fetch --tags
          if git rev-parse "$TAG" >/dev/null 2>&1; then
            echo "tag=$TAG" >> "$GITHUB_OUTPUT"
            echo "Tag $TAG already exists"
          else
            git config user.name "github-actions[bot]"
            git config user.email "github-actions[bot]@users.noreply.github.com"
            git tag "$TAG"
            git push origin "$TAG"
            echo "tag=$TAG" >> "$GITHUB_OUTPUT"
            echo "Created tag $TAG"
          fi

      - name: Ensure GitHub release
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          TAG: ${{ steps.ensure_tag.outputs.tag }}
          VERSION: ${{ steps.get_version.outputs.version }}
        run: |
          if gh release view "$TAG" >/dev/null 2>&1; then
            echo "Release $TAG already exists"
          else
            gh release create "$TAG" --title "CodeNomad v${VERSION}" --generate-notes
          fi

  build-and-upload:
    needs: prepare-release
    uses: ./.github/workflows/build-and-upload.yml
    with:
      version: ${{ needs.prepare-release.outputs.version }}
      tag: ${{ needs.prepare-release.outputs.tag }}
      release_name: CodeNomad v${{ needs.prepare-release.outputs.version }}
    secrets: inherit

  publish-server:
    needs:
      - prepare-release
      - build-and-upload
    if: ${{ needs.build-and-upload.result == 'success' }}
    uses: ./.github/workflows/manual-npm-publish.yml
    with:
      version: ${{ needs.prepare-release.outputs.version }}
      dist_tag: latest
    secrets: inherit
