name: Docker Build & Test

on:
  push:
    branches:
      - main
    paths-ignore:
      - '**.md'
  pull_request:
    branches:
      - main
    paths-ignore:
      - '**.md'
  workflow_dispatch:

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

jobs:
  build:
    runs-on: ubuntu-latest
    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: Build Docker image (Test)
        uses: docker/build-push-action@v5
        with:
          context: .
          file: ./Dockerfile
          platforms: linux/amd64,linux/arm64
          push: false
          tags: |
            katelyatv:latest
            katelyatv:${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Log in to GitHub Container Registry
        if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build and push Docker image
        if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
        uses: docker/build-push-action@v5
        with:
          context: .
          file: ./Dockerfile
          platforms: linux/amd64,linux/arm64
          push: true
          tags: |
            ghcr.io/${{ github.repository_owner }}/katelyatv:latest
            ghcr.io/${{ github.repository_owner }}/katelyatv:${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

  test:
    runs-on: ubuntu-latest
    needs: build
    if: always()

    steps:
      - name: Test Summary
        run: |
          echo "✅ Docker build completed successfully!"
          echo "📦 Multi-platform support: linux/amd64, linux/arm64"
          echo "🔄 Cache optimization enabled"
          if [ "${{ github.event_name }}" != "pull_request" ] && [ "${{ github.ref }}" == "refs/heads/main" ]; then
            echo "🚀 Images pushed to GitHub Container Registry"
          else
            echo "🧪 Build test completed (no push for PR/non-main branch)"
          fi
