name: Docker Image CI

on:
  push:
    branches: [master]

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  build:
    runs-on: ubuntu-latest
    timeout-minutes: 30
    steps:
      - uses: actions/checkout@v4

      - name: Validate Docker credentials
        run: |
          set -euo pipefail
          if [ -z "${{ secrets.DOCKER_USERNAME }}" ] || [ -z "${{ secrets.DOCKER_TOKEN }}" ]; then
            echo "::error::Docker credentials not configured. Please set DOCKER_USERNAME and DOCKER_TOKEN secrets."
            exit 1
          fi

      - name: Set variables
        id: vars
        run: |
          set -euo pipefail
          echo "package_name=$(sed -En 's/name[[:space:]]*=[[:space:]]*"([^"]+)"/\1/p' Cargo.toml | head -1)" >> $GITHUB_OUTPUT
          echo "package_version=$(sed -En 's/version[[:space:]]*=[[:space:]]*"([^"]+)"/\1/p' Cargo.toml | head -1)" >> $GITHUB_OUTPUT
          echo "dockerhub_org=${{ github.repository_owner }}" >> $GITHUB_OUTPUT

      - name: Display variables
        run: |
          echo "Package: ${{ steps.vars.outputs.package_name }}"
          echo "Version: ${{ steps.vars.outputs.package_version }}"
          echo "Org: ${{ steps.vars.outputs.dockerhub_org }}"

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

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

      - name: Prepare Docker context
        run: |
          set -euo pipefail
          if [ -f docker/.dockerignore ]; then
            mv docker/.dockerignore .dockerignore
          else
            echo "Warning: docker/.dockerignore not found, using default"
          fi

      - name: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: .
          file: docker/Dockerfile
          push: true
          platforms: linux/amd64,linux/arm64
          tags: |
            ${{ steps.vars.outputs.dockerhub_org }}/${{ steps.vars.outputs.package_name }}:${{ steps.vars.outputs.package_version }}
            ${{ steps.vars.outputs.dockerhub_org }}/${{ steps.vars.outputs.package_name }}:latest
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Verify Docker build
        run: |
          set -euo pipefail
          echo "✅ Docker image built and pushed successfully"
          echo "Repository: ${{ steps.vars.outputs.dockerhub_org }}/${{ steps.vars.outputs.package_name }}"
          echo "Tags:"
          echo "  - ${{ steps.vars.outputs.package_version }}"
          echo "  - latest"
