#!/usr/bin/env bash
# Tests review eligibility: only customers who hired & completed can rate.
set -euo pipefail

API="${API_URL:-http://localhost:4000/api}"
PASS="${DEMO_PASSWORD:-Password123!}"

pass=0
fail=0

login() {
  curl -s -X POST "$API/auth/login" \
    -H 'Content-Type: application/json' \
    -d "{\"identifier\":\"$1\",\"password\":\"$PASS\"}" \
    | python3 -c "import sys,json; d=json.load(sys.stdin); assert d.get('success'), d.get('error','login failed'); print(d['data']['accessToken'])"
}

assert_api_fail() {
  local label="$1"
  local body="$2"
  local expect="$3"
  if echo "$body" | python3 -c "import sys,json; d=json.load(sys.stdin); exit(0 if not d.get('success') and '$expect' in (d.get('error') or '') else 1)"; then
    echo "  PASS: $label"
    pass=$((pass + 1))
  else
    echo "  FAIL: $label"
    echo "    Response: $body"
    fail=$((fail + 1))
  fi
}

assert_api_ok() {
  local label="$1"
  local body="$2"
  if echo "$body" | python3 -c "import sys,json; d=json.load(sys.stdin); exit(0 if d.get('success') else 1)"; then
    echo "  PASS: $label"
    pass=$((pass + 1))
  else
    echo "  FAIL: $label"
    echo "    Response: $body"
    fail=$((fail + 1))
  fi
}

echo "=== Review eligibility API tests ==="
echo

# Find a completed job with an existing review (from seed)
REVIEWED_JOB=$(curl -s "$API/reviews/worker/b4c4bad2-8d0e-4823-b56a-b84d4eb859cf" \
  | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['data'][0]['jobId'] if d.get('data') else '')")

if [ -z "$REVIEWED_JOB" ]; then
  echo "WARN: No seeded reviews found — some tests skipped"
else
  echo "1. Unrelated customer cannot review someone else's job"
  ANA_TOKEN=$(login "ana@example.com")
  BODY=$(curl -s -X POST "$API/reviews" \
    -H "Authorization: Bearer $ANA_TOKEN" \
    -H 'Content-Type: application/json' \
    -d "{\"jobId\":\"$REVIEWED_JOB\",\"qualityRating\":5,\"communicationRating\":5,\"punctualityRating\":5}")
  assert_api_fail "blocks wrong customer" "$BODY" "own jobs"

  echo "2. Eligible check returns not eligible for wrong customer"
  BODY=$(curl -s "$API/reviews/eligible/$REVIEWED_JOB" -H "Authorization: Bearer $ANA_TOKEN")
  assert_api_fail "eligible endpoint blocks wrong customer" "$(echo "$BODY" | python3 -c "import sys,json; d=json.load(sys.stdin); d['success']=False; d['error']=d['data'].get('reason',''); import json; print(json.dumps(d))")" "own jobs"

  echo "3. Customer who already reviewed cannot submit again"
  CUST_TOKEN=$(login "customer@example.com")
  BODY=$(curl -s -X POST "$API/reviews" \
    -H "Authorization: Bearer $CUST_TOKEN" \
    -H 'Content-Type: application/json' \
    -d "{\"jobId\":\"$REVIEWED_JOB\",\"qualityRating\":5,\"communicationRating\":5,\"punctualityRating\":5}")
  assert_api_fail "blocks duplicate review" "$BODY" "already submitted"
fi

echo "4. Worker role cannot submit reviews"
WORKER_TOKEN=$(login "marco@worker.com")
OPEN_JOB=$(curl -s "$API/jobs?limit=1" | python3 -c "import sys,json; print(json.load(sys.stdin)['data'][0]['id'])")
BODY=$(curl -s -X POST "$API/reviews" \
  -H "Authorization: Bearer $WORKER_TOKEN" \
  -H 'Content-Type: application/json' \
  -d "{\"jobId\":\"$OPEN_JOB\",\"qualityRating\":5,\"communicationRating\":5,\"punctualityRating\":5}")
if echo "$BODY" | python3 -c "import sys,json; d=json.load(sys.stdin); exit(0 if not d.get('success') else 1)"; then
  echo "  PASS: worker cannot submit review"
  pass=$((pass + 1))
else
  echo "  FAIL: worker should not submit review"
  echo "    Response: $BODY"
  fail=$((fail + 1))
fi

echo "5. Open job cannot be reviewed"
MARIA_TOKEN=$(login "maria@example.com")
MARIA_JOB=$(curl -s "$API/jobs/my/list?limit=1" -H "Authorization: Bearer $MARIA_TOKEN" \
  | python3 -c "import sys,json; jobs=json.load(sys.stdin)['data']; print(jobs[0]['id'] if jobs else '')")
if [ -n "$MARIA_JOB" ]; then
  BODY=$(curl -s "$API/reviews/eligible/$MARIA_JOB" -H "Authorization: Bearer $MARIA_TOKEN")
  REASON=$(echo "$BODY" | python3 -c "import sys,json; print(json.load(sys.stdin)['data'].get('reason',''))")
  if echo "$REASON" | grep -qi "completed"; then
    echo "  PASS: open job not eligible ($REASON)"
    pass=$((pass + 1))
  else
    echo "  FAIL: expected completed-job message, got: $REASON"
    fail=$((fail + 1))
  fi
else
  echo "  SKIP: no maria jobs"
fi

echo "6. GET /reviews/pending and /reviews/my (customer auth)"
BODY=$(curl -s "$API/reviews/pending" -H "Authorization: Bearer $MARIA_TOKEN")
assert_api_ok "pending reviews list" "$BODY"
BODY=$(curl -s "$API/reviews/my" -H "Authorization: Bearer $MARIA_TOKEN")
assert_api_ok "my reviews list" "$BODY"

echo "7. Unauthenticated request rejected"
HTTP=$(curl -s -o /dev/null -w "%{http_code}" -X POST "$API/reviews" \
  -H 'Content-Type: application/json' \
  -d "{\"jobId\":\"00000000-0000-0000-0000-000000000001\",\"qualityRating\":5,\"communicationRating\":5,\"punctualityRating\":5}")
if [ "$HTTP" = "401" ]; then
  echo "  PASS: unauthenticated returns 401"
  pass=$((pass + 1))
else
  echo "  FAIL: expected 401, got $HTTP"
  fail=$((fail + 1))
fi

echo
echo "=== Results: $pass passed, $fail failed ==="
[ "$fail" -eq 0 ]
