name: Build and Push Docker Images

on:
  push:
    branches:
      - main
    tags:
      - 'v*.*.*'
  pull_request:
    branches:
      - main

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

      - name: Set up Go
        uses: actions/setup-go@v4
        with:
          go-version: 1.22

      - name: Install mupdf
        run: sudo apt-get install -y mupdf

      - name: Set library path
        run: echo "/usr/lib" | sudo tee -a /etc/ld.so.conf.d/mupdf.conf && sudo ldconfig

      - name: Install dependencies
        run: go mod download

      - name: Run Go tests
        run: go test ./...

      - name: Set up Node.js
        uses: actions/setup-node@v3
        with:
          node-version: 20

      - name: Cache npm dependencies
        uses: actions/cache@v3
        with:
          path: ~/.npm
          key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
          restore-keys: |
            ${{ runner.os }}-node-

      - name: Install frontend dependencies
        run: npm install
        working-directory: web-app

      - name: Run frontend tests
        run: npm test
        working-directory: web-app

  build-and-push:
    runs-on: ubuntu-latest
    needs: test
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

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

      - name: Log in to Docker Hub
        if: ${{ github.event_name != 'pull_request' }}
        uses: docker/login-action@v2
        with:
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}

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

      - name: Set Docker tags
        id: set_tags
        run: |
          echo "TAGS=icereed/paperless-gpt:unreleased" >> $GITHUB_ENV
          if [[ "${GITHUB_REF}" == "refs/heads/main" ]]; then
            echo "TAGS=icereed/paperless-gpt:unreleased" >> $GITHUB_ENV
          elif [[ "${GITHUB_REF_TYPE}" == "tag" ]]; then
            VERSION=${GITHUB_REF#refs/tags/}
            echo "TAGS=icereed/paperless-gpt:latest,icereed/paperless-gpt:${VERSION}" >> $GITHUB_ENV
          fi

      - name: Build and push Docker images
        id: docker_build
        uses: docker/build-push-action@v4
        with:
          context: .
          platforms: linux/amd64,linux/arm64
          push: ${{ github.event_name != 'pull_request' }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
          tags: ${{ env.TAGS }}
