name: "Pre-release Build"

on:
  workflow_dispatch: {}
  schedule:
    - cron: '0 2 * * *'

# Ensure only one nightly run at a time — concurrent runs would race on the tag/release.
concurrency:
  group: prerelease
  cancel-in-progress: true

# Minimal permissions at workflow level - each job specifies what it needs
permissions: {}

jobs:
  prerelease:
    name: Build and publish pre-release
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - name: Checkout
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
        with:
          fetch-depth: 0
          persist-credentials: false

      - name: Configure git credentials
        run: |
          git remote set-url origin "https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}.git"

      - name: Set up tools
        uses: jdx/mise-action@1648a7812b9aeae629881980618f079932869151 # v4

      - name: Cache Go modules
        uses: actions/cache@v4
        with:
          path: |
            ~/go/pkg/mod
            ~/.cache/go-build
          key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
          restore-keys: ${{ runner.os }}-go-

      - name: Delete existing nightly release and tag
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          gh release delete nightly --yes --cleanup-tag 2>/dev/null || true

      - name: Create nightly tag on HEAD
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
          git tag -f nightly
          git push origin nightly --force

      - name: Run GoReleaser
        uses: goreleaser/goreleaser-action@ec59f474b9834571250b370d4735c50f8e2d1e29 # v7.0.0
        with:
          distribution: goreleaser
          version: "v2.15.4"
          args: release --config .goreleaser-prerelease.yaml --clean --skip=validate --timeout=60m
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Summary
        run: |
          SHORT_SHA=$(git rev-parse --short HEAD)
          echo "### ✅ Pre-release build published" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "- **Commit:** \`${SHORT_SHA}\`" >> $GITHUB_STEP_SUMMARY
          echo "- **Release:** [nightly](https://github.com/${{ github.repository }}/releases/tag/nightly)" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "Install with:" >> $GITHUB_STEP_SUMMARY
          echo '```sh' >> $GITHUB_STEP_SUMMARY
          echo "curl -fsSL https://download.kubeasy.dev/install.sh | KUBEASY_VERSION=nightly sh" >> $GITHUB_STEP_SUMMARY
          echo '```' >> $GITHUB_STEP_SUMMARY
