name: Test, Build and Publish

on:
  push:
    branches:
      - main
    tags:
      - '*'
  pull_request:
  workflow_dispatch:

env:
  REGISTRY: forge.mdiluz.io

jobs:

  # Run the tests scripts
  test:
    runs-on: ubuntu-22.04
    steps:
    - uses: actions/checkout@v4
      with:
        fetch-depth: 0
    - name: Set up Python
      uses: actions/setup-python@v5
      with:
        python-version: 3.12
        cache: pip
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        python -m pip install -r requirements.txt
    - name: Run tests
      run: |
        python tests/test.py

  # Build and push the docker images
  build-and-push-images:
    runs-on: ubuntu-22.04
    needs: test

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
     
      - name: Log in to the Container registry
        uses: docker/login-action@65b78e6e13532edd9afa3aa52ac7964289d1a9c1
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ env.GITHUB_ACTOR }}
          password: ${{ secrets.PACKAGE_PAT }}

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

      - name: Extract metadata (tags, labels) for Docker
        id: meta
        uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7
        with:
          images: ${{ env.REGISTRY }}/${{ env.GITHUB_REPOSITORY }}
          tags: |
            type=ref,event=tag
            type=ref,event=branch
            type=ref,event=pr
            type=edge,branch=main

      - name: Build and push Docker image
        id: push
        uses: docker/build-push-action@f2a1d5e99d037542a71f64918e516c093c6f3fc4
        with:
          context: .
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
