#!/usr/bin/env bash
# Runs the whole AssetTrack test suite against a RUNNING server and prints one verdict.
#   BASE=http://localhost:3000 DB_PASS=... bash tests/qa/run-all.sh        (from the application folder)
# Needs: the server running, the DEMO data seeded (npm run seed), and DB_* variables pointing at the SAME database.
# WARNING: these tests create users, items, bills and change POS settings. Run them on a TEST database, never on live data.
# FAST=1 skips the 62-second pauses (they only exist so the per-user rate limit window resets between heavy scripts).
cd "$(dirname "$0")/../.." || exit 2
export BASE="${BASE:-http://localhost:3000}"
fail=0; pause() { [ "${FAST:-0}" = "1" ] || sleep 62; }
step() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; }
qa() { # name script
  step "$1"; out=$(node "tests/qa/$2" 2>&1); echo "$out" | grep -E "✗|⚑|done:|FATAL" ; 
  echo "$out" | grep -q "FATAL" && fail=1
  failed=$(echo "$out" | sed -n 's/.*done: [0-9]* passed, \([0-9]*\) failed.*/\1/p' | tail -1); [ -n "$failed" ] && [ "$failed" != "0" ] && fail=1; true; }

step "Existing unit tests"
for t in pricing charges orders; do printf '%-9s' "$t:"; npm run -s "test:$t" 2>&1 | tail -1; done
npm run -s test:pricing 2>&1 | grep -q "invariant failures: 0" || fail=1
npm run -s test:charges 2>&1 | grep -q "passed" || fail=1
npm run -s test:orders 2>&1 | grep -q "passed" || fail=1
step "Existing POS end-to-end"; npm run -s test:pos 2>&1 | tail -3; npm run -s test:pos 2>&1 | grep -q "checks passed" || fail=1

qa "P1 Inventory functions & costing" p1_inventory.js; pause
qa "P2 POS correctness & inventory<->POS flow" p2_pos.js; pause
qa "P7 Item-edit race & manager-approval race" p7_open_items.js; pause

step "P4 Concurrency matrix (every cell must be 0/6)"
out=$(node tests/qa/p4_diag.js 2>&1); echo "$out" | tail -8; echo "$out" | grep -qE "inconsistency: [1-9]|Error" && fail=1; pause

step "P5 Phantom cost layers (expect exactly 1 = the genuine opening layer)"
n=$(node tests/qa/p5_phantom.js 2>&1 | grep -c '"by_user":null'); echo "layers without a user: $n"; [ "$n" = "1" ] || fail=1; pause

qa "P3 Races + production load + audits" p3_load.js

echo; if [ "$fail" = "0" ]; then printf '\033[32mALL TESTS PASSED\033[0m\n'; else printf '\033[31mFAILURES — see above\033[0m\n'; fi; exit $fail
