name: Build and Push Docker Image

on:
  pull_request:
    types: [closed]
    branches:
      - main
  workflow_dispatch:
    inputs:
      tag:
        description: 'Docker image tag'
        required: true
        default: 'latest'

env:
  DOCKERHUB_IMAGE: pyd4vinci/scrapling
  GHCR_IMAGE: ghcr.io/${{ github.repository_owner }}/scrapling

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
    - name: Checkout repository
      uses: actions/checkout@v6

    - name: Set up Docker Buildx
      uses: docker/setup-buildx-action@v3
      with:
        platforms: linux/amd64,linux/arm64

    - name: Log in to Docker Hub
      uses: docker/login-action@v3
      with:
        registry: docker.io
        username: ${{ secrets.DOCKER_USERNAME }}
        password: ${{ secrets.DOCKER_PASSWORD }}

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

    - name: Extract metadata
      id: meta
      uses: docker/metadata-action@v5
      with:
        images: |
          ${{ env.DOCKERHUB_IMAGE }}
          ${{ env.GHCR_IMAGE }}
        tags: |
          type=ref,event=branch
          type=ref,event=pr
          type=semver,pattern={{version}}
          type=semver,pattern={{major}}.{{minor}}
          type=semver,pattern={{major}}
          type=raw,value=latest,enable={{is_default_branch}}
        labels: |
          org.opencontainers.image.title=Scrapling
          org.opencontainers.image.description=An undetectable, powerful, flexible, high-performance Python library that makes Web Scraping easy and effortless as it should be!
          org.opencontainers.image.vendor=D4Vinci
          org.opencontainers.image.licenses=BSD
          org.opencontainers.image.url=https://scrapling.readthedocs.io/en/latest/
          org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
          org.opencontainers.image.documentation=https://scrapling.readthedocs.io/en/latest/

    - name: Build and push Docker image
      uses: docker/build-push-action@v6
      with:
        context: .
        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
        build-args: |
          BUILDKIT_INLINE_CACHE=1

    - name: Image digest
      run: echo ${{ steps.build.outputs.digest }}