name: Build Docker Image

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

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v3
        with:
          fetch-depth: 0

      - name: Set up Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Run tests
        run: npm test || true

      - name: Setup Docker Buildx
        uses: docker/setup-buildx-action@v2

      - name: Extract metadata for Docker
        id: meta
        uses: docker/metadata-action@v4
        with:
          images: local/personal-website
          tags: |
            type=ref,event=branch
            type=ref,event=pr
            type=sha

      - name: Build Docker image (no push)
        uses: docker/build-push-action@v4
        with:
          context: .
          push: false
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
          outputs: type=docker,dest=/tmp/image.tar

      - name: Save Docker image as artifact
        uses: actions/upload-artifact@v3
        with:
          name: docker-image
          path: /tmp/image.tar
          retention-days: 1