# Publish a container image to GitHub Container Registry on every
# version tag push (e.g. `v1.2.3`). Pulls the version straight from
# the tag — keep `package.json` `version` in sync with the tag for
# clarity, but the tag is what drives the image label.
#
# Why GHCR (not Docker Hub):
#   - Free for public images (no rate limits on anonymous pulls)
#   - Scoped to the same `stevenvelozo` namespace as the source repo
#   - One step to wire: GITHUB_TOKEN already has `packages: write`
#
# Image lands at:
#   ghcr.io/stevenvelozo/meadow-integration:<version>
#   ghcr.io/stevenvelozo/meadow-integration:latest   (only on the
#                                                     highest stable tag)
#
# Manual run: `Actions → Publish container image → Run workflow`,
# pass an explicit tag for ad-hoc rebuilds without bumping a release.

name: Publish container image

on:
  push:
    tags:
      - 'v*.*.*'        # v1.2.3, v1.2.3-beta.1, etc.
  workflow_dispatch:
    inputs:
      tag:
        description: 'Tag to apply (e.g. dev or 1.2.3-test). `latest` is reserved for stable tag pushes.'
        required: true
        default: 'dev'

permissions:
  contents: read
  packages: write   # required to push to ghcr.io under the repo owner

jobs:
  build-and-push:
    runs-on: ubuntu-latest

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

      - name: Set up QEMU (multi-arch support)
        uses: docker/setup-qemu-action@v3

      - 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 }}

      # Derives image tags from the git ref:
      #   v1.2.3       → :1.2.3 + :1.2 + :1 + :latest (semver patterns)
      #   v1.2.3-beta  → :1.2.3-beta only (pre-release, no `latest`)
      # workflow_dispatch → :<inputs.tag> only
      - name: Compute image tags
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ghcr.io/${{ github.repository_owner }}/meadow-integration
          tags: |
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=semver,pattern={{major}}
            type=raw,value=${{ github.event.inputs.tag }},enable=${{ github.event_name == 'workflow_dispatch' }}

      # linux/amd64 + linux/arm64 covers the common cases (CI hosts,
      # Apple Silicon dev boxes, and most cloud runners). Add more
      # platforms as deployment targets emerge.
      - name: Build and push
        uses: docker/build-push-action@v5
        with:
          context: .
          file: ./Dockerfile
          platforms: linux/amd64,linux/arm64
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
