name: Test and deploy

on:
  push:
    branches: [master]
  workflow_dispatch:

concurrency:
  group: roast-command-center-production
  cancel-in-progress: false

jobs:
  test-and-deploy:
    runs-on: unraid
    steps:
      - name: Check out the pushed revision
        uses: https://github.com/actions/checkout@v4

      # Host-mode action workspaces are ephemeral runner internals. Copy the checked-out SHA
      # to a normal writable path so Node tests and Docker Compose see the same source tree.
      - name: Prepare isolated build directory
        run: |
          export CI_WORKDIR="/tmp/roast-command-center-${GITHUB_RUN_ID}"
          rm -rf "$CI_WORKDIR"
          mkdir -p "$CI_WORKDIR"
          cp -a ./. "$CI_WORKDIR/"
          echo "CI_WORKDIR=$CI_WORKDIR" >> "$GITHUB_ENV"

      - name: Install dependencies
        run: cd "$CI_WORKDIR" && npm ci

      - name: Test
        run: cd "$CI_WORKDIR" && npm test

      - name: Deploy to Unraid Docker
        run: |
          cd "$CI_WORKDIR"
          docker compose \
            --project-name roast_command_center \
            --env-file /run/roast-production.env \
            -f docker-compose.yml \
            up -d --build --remove-orphans

      - name: Verify the running container
        run: |
          cd "$CI_WORKDIR"
          for attempt in {1..15}; do
            if docker compose \
              --project-name roast_command_center \
              --env-file /run/roast-production.env \
              -f docker-compose.yml \
              exec -T app node -e "fetch('http://127.0.0.1:8090/').then((response) => process.exit(response.ok ? 0 : 1))"; then
              break
            fi
            if [ "$attempt" -eq 15 ]; then
              exit 1
            fi
            sleep 2
          done
          curl --fail --retry 10 --retry-delay 2 https://roast.srmr.xyz/
