name: Build and Push Docker Image

on:
  push:
    branches:
      - main        # Adjust if your main branch is different
    tags:
      - 'v*.*.*'    # Trigger on version tags

env:
  REGISTRY: git.cmzi.uk

  # Use 'github' context variables as fallbacks for repo owner and name
  IMAGE_BASE_NAME: ${{ github.repository }}

jobs:
  build-and-push:
    runs-on: alpine-latest # Or your preferred runner with Docker
    permissions:
      contents: read
      packages: write # Still required for pushing to the registry

    steps:
      - name: Check out code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0 # Recommended for metadata action

      # 2. Set up Node.js environment
      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '18.x' # Specify your desired Node.js version
          cache: 'yarn'       # Enable caching for yarn dependencies

      - name: Install Yarn dependencies
        run: yarn install --frozen-lockfile # Use --frozen-lockfile for reproducible installs

      - name: Build project
        run: yarn build

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

      - name: Log in to Forgejo Container Registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }} # Use the registry URL defined above
          # Use 'github.actor' as a fallback for the username context
          username: ${{ github.repository_owner }}
          # Use the Forgejo-specific token - this SHOULD still work if Actions are enabled
          password: ${{ secrets.RUNNER_TOKEN }}

      - name: Extract metadata (tags, labels) for Docker
        id: meta
        uses: docker/metadata-action@v5
        with:
          # Construct the full image name using the defined REGISTRY and IMAGE_BASE_NAME
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_BASE_NAME }}
          tags: |
            # Use 'github.ref' for branch/tag detection
            type=raw,value=latest,enable=${{ github.ref == format('refs/heads/{0}', 'main') }} # Adjust 'main' if needed
            type=ref,event=branch
            type=ref,event=tag
            type=sha,format=short # Tag with short Git SHA
          # Add standard OCI labels using github context
          labels: |
            org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
            org.opencontainers.image.revision=${{ github.sha }}
            org.opencontainers.image.ref.name=${{ github.ref_name }}

      - name: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: .
          file: ./Dockerfile
          push: true
          tags: ${{ steps.meta.outputs.tags }}    # Use tags from metadata step
          labels: ${{ steps.meta.outputs.labels }}  # Use labels from metadata step
          cache-from: type=gha
          cache-to: type=gha,mode=max