name: Tests and Sanity Run

on:
  workflow_call:
    inputs:
      node-version:
        description: "Node version"
        required: false
        default: '20.x'
        type: string
      ref:
        description: "Ref to checkout"
        required: false
        type: string

jobs:
  test:
    name: Tests / Build / Sanity Run
    runs-on: ubuntu-latest
    steps:
      - name: Check out the repo
        uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 #v4.3.0
        with:
          ref: ${{ inputs.ref }}
          persist-credentials: false
      - name: Use Node.js
        uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 #4.4.0
        with:
          node-version: ${{ inputs.node-version }}
          cache: 'npm'

      - name: Install concurrently
        run: npm install -g concurrently

      - name: Install dev dependencies
        run: npm run install:parallel

      - name: Test Backend
        run: npm run test

      - name: Build
        run: npm run build:parallel
      
        # remove modules that might include dev stuff
        # so that in the next step we are sure that prod-only runs work correctly
      - name: Install Prod Deps
        run: |
          rm -rf node_modules && \
          rm -rf docsite/node_modules && \
          NODE_ENV=production npm ci --omit=dev

        # run app for 10 seconds as sanity check to see if it errors for any reason
        # easy testcase for missing packages and init errors
      - name: Sanity Run
        run: |
          set +e
          export NODE_ENV=production
          timeout --preserve-status 10s node node_modules/.bin/tsx src/backend/index.ts
          exitcode="$?"
          if [[ "$exitcode" -eq 143 ]] || [[ "$exitcode" -eq 137 ]]; then
            echo "App stayed up long enough and exited with expected status"
            exit 0
          else
            echo "App exited with unexpected code $exitcode"
            exit "$exitcode"
          fi
