name: Build Docker Image

# Trigger when a PR to main/develop is completed.
on:
  pull_request:
    branches:
      - main
      - develop
    types:
      - closed

jobs:
  build-and-push:
    if: ${{ github.event.pull_request.merged == true }}
    runs-on: ubuntu-latest
    steps:
      # Fetch the repository content for the Docker build context.
      - name: Checkout repository
        uses: actions/checkout@v4

      # Enable Buildx for BuildKit features (incl. SSH mount support).
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      # Authenticate against the container registry before pushing images.
      - name: Log in to container registry
        uses: docker/login-action@v3
        with:
          registry: git.envipath.com
          username: ${{ secrets.CI_REGISTRY_USER }}
          password: ${{ secrets.CI_REGISTRY_PASSWORD }}

      # Generate image tags/labels:
      # - PRs targeting main get "latest" and "main-sha"
      # - PRs targeting develop get "dev" and "dev-sha"
      - name: Extract metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: git.envipath.com/envipath/envipy
          tags: |
            type=raw,value=latest,enable=${{ github.event.pull_request.base.ref == 'main' }}
            type=sha,prefix=main-,enable=${{ github.event.pull_request.base.ref == 'main' }}
            type=raw,value=dev,enable=${{ github.event.pull_request.base.ref == 'develop' }}
            type=sha,prefix=dev-,enable=${{ github.event.pull_request.base.ref == 'develop' }}

      # Load SSH key so Docker can pull private git+ssh dependencies during build.
      - name: Setup SSH for private git dependencies
        uses: webfactory/ssh-agent@v0.9.0
        with:
          ssh-private-key: ${{ secrets.ENVIPY_CI_PRIVATE_KEY }}

      # Build and push the production image; forward SSH agent without registry cache reuse.
      - name: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: .
          file: Dockerfile
          push: true
          ssh: default
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
