name: Develop Pre-Release

on:
  schedule:
    # Nightly build of dev (only if dev has new commits)
    - cron: "0 1 * * *"
  workflow_dispatch:

permissions:
  actions: read
  id-token: write
  contents: write

concurrency:
  group: dev-prerelease
  cancel-in-progress: true

jobs:
  gate:
    runs-on: ubuntu-latest
    outputs:
      run: ${{ steps.gate.outputs.run }}
      dev_sha: ${{ steps.gate.outputs.dev_sha }}
      version_suffix: ${{ steps.gate.outputs.version_suffix }}
    steps:
      - name: Decide whether to run
        id: gate
        shell: bash
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          set -euo pipefail

          api() {
            curl -sS \
              -H "Authorization: Bearer ${GH_TOKEN}" \
              -H "Accept: application/vnd.github+json" \
              -H "X-GitHub-Api-Version: 2022-11-28" \
              "$1"
          }

          DEV_SHA=$(api "https://api.github.com/repos/${GITHUB_REPOSITORY}/git/ref/heads/dev" | jq -r '.object.sha')
          if [ -z "$DEV_SHA" ] || [ "$DEV_SHA" = "null" ]; then
            echo "Failed to resolve dev head SHA" >&2
            exit 1
          fi

          DATE=$(date -u +%Y%m%d)
          SHA8="${DEV_SHA::8}"
          VERSION_SUFFIX="-dev-${DATE}-${SHA8}"

          SHOULD_RUN="false"
          if [ "${GITHUB_EVENT_NAME}" = "workflow_dispatch" ]; then
            SHOULD_RUN="true"
          else
            # Nightly: only run if dev has advanced since last successful dev-release build.
            LAST_SHA=$(api "https://api.github.com/repos/${GITHUB_REPOSITORY}/actions/workflows/dev-release.yml/runs?branch=dev&status=success&per_page=1" | jq -r '.workflow_runs[0].head_sha // empty')
            if [ -z "${LAST_SHA}" ]; then
              SHOULD_RUN="true"
            elif [ "${LAST_SHA}" != "${DEV_SHA}" ]; then
              SHOULD_RUN="true"
            fi
          fi

          echo "run=${SHOULD_RUN}" >> "$GITHUB_OUTPUT"
          echo "dev_sha=${DEV_SHA}" >> "$GITHUB_OUTPUT"
          echo "version_suffix=${VERSION_SUFFIX}" >> "$GITHUB_OUTPUT"

  prerelease:
    needs: gate
    if: ${{ needs.gate.outputs.run == 'true' }}
    uses: ./.github/workflows/reusable-release.yml
    with:
      ref: ${{ needs.gate.outputs.dev_sha }}
      version_suffix: ${{ needs.gate.outputs.version_suffix }}
      npm_package_name: "@neuralnomads/codenomad-dev"
      dist_tag: latest
      prerelease: true
      release_ui: false
    secrets: inherit
