name: Build and Push Docker Image

on:
  push:
    branches:
      - main
      - beta
      - dev
      - github-actions-ci
    paths:
      - 'src/**'
      - 'helm/Chart.yaml'
      - 'config.yaml'
      - 'Dockerfile'
      - 'requirements.txt'
      - 'entrypoint.sh'
      - '.github/workflows/docker-build-push.yml'
    tags:
      - 'v*.*.*'
  release:
    types: [published]
  workflow_dispatch:

env:
  REGISTRY: ${{ vars.DOCKER_REGISTRY }}
  IMAGE_NAME: ${{ vars.DOCKER_IMAGE_NAME }}

jobs:
  build-and-push:
    runs-on: self-hosted
    permissions:
      contents: read
      packages: write

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

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

      - name: Log in to Container Registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract appVersion from Chart.yaml and determine tags
        id: tags
        run: |
          APP_VERSION=$(grep '^appVersion:' helm/Chart.yaml | awk '{print $2}' | tr -d '"' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
          
          if [ -z "$APP_VERSION" ]; then
            echo "Error: Could not extract appVersion from Chart.yaml"
            exit 1
          fi
          
          if [[ "${{ github.ref_name }}" == "main" ]]; then
            TAGS="${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${APP_VERSION},${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest"
          else
            TAGS="${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${APP_VERSION}-${{ github.ref_name }}"
          fi
          
          echo "tags=$TAGS" >> $GITHUB_OUTPUT

      - name: Extract metadata (tags, labels)
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}

      - name: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: .
          file: ./Dockerfile
          push: true
          tags: ${{ steps.tags.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache
          cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache,mode=max

      - name: Image digest
        run: |
          echo "Image built and pushed with tags:"
          echo "${{ steps.tags.outputs.tags }}"
