name: Docker Build and Push

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

jobs:
  docker:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Get version from package.json
        id: package-version
        run: echo "version=$(node -p "require('./package.json').version")" >> $GITHUB_OUTPUT

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3

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

      - name: Login to Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Extract metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: kuekhaoyang/kvideo
          tags: |
            type=semver,pattern={{version}},value=v${{ steps.package-version.outputs.version }}
            type=semver,pattern={{major}}.{{minor}},value=v${{ steps.package-version.outputs.version }}
            type=raw,value=latest
            type=raw,value=${{ steps.package-version.outputs.version }}

      - name: Debug - List files
        run: |
          echo "=== Files in current directory ==="
          ls -la
          echo "=== Node modules status ==="
          if [ -d "node_modules" ]; then echo "node_modules exists"; else echo "node_modules NOT found"; fi
          echo "=== Lockfiles ==="
          ls -la | grep -E "lock|yarn" || echo "No lockfiles found"

      - name: Build and push
        uses: docker/build-push-action@v5
        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
