name: Nightly

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

permissions:
  contents: read

jobs:
  setup:
    runs-on: ubuntu-latest
    outputs:
      branch: ${{ steps.branch.outputs.branch }}
      date: ${{ steps.date.outputs.date }}

    steps:
      - name: Find active release branch
        id: branch
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          branch=$(gh api "repos/${{ github.repository }}/git/matching-refs/heads/release/v" \
            --jq '[.[].ref | ltrimstr("refs/heads/")] | map(ltrimstr("refs/heads/")) | .[]' \
            | sort -V | tail -1 || true)
          if [[ -z "$branch" ]]; then
            branch="main"
          fi
          echo "branch=$branch" >> "$GITHUB_OUTPUT"
          echo "Active branch: $branch"

      - name: Get date
        id: date
        run: echo "date=$(date -u +%Y%m%d)" >> "$GITHUB_OUTPUT"

  build-docker:
    needs: setup
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ needs.setup.outputs.branch }}
          persist-credentials: false

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Log in to GHCR
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build and push Docker image
        uses: docker/build-push-action@v6
        with:
          context: .
          platforms: linux/amd64,linux/arm64
          push: true
          tags: |
            ghcr.io/got-feedback/feedback:nightly
            ghcr.io/got-feedback/feedback:nightly-${{ needs.setup.outputs.date }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
