#!/usr/bin/env bash
set -uo pipefail

BASE="https://petshop-backend.nicepond-c7280126.westus2.azurecontainerapps.io/api/v1"
PASS=0 FAIL=0

CLEANUP_USER_IDS=()
CLEANUP_PRODUCT_IDS=()
CLEANUP_CATEGORY_IDS=()
CLEANUP_PET_IDS=()
CLEANUP_MYPET_IDS=()
CLEANUP_SERVICE_IDS=()
CLEANUP_STORE_IDS=()
CLEANUP_APPT_IDS=()
CLEANUP_ADOPTION_IDS=()
CLEANUP_SALE_IDS=()
CLEANUP_COUPON_IDS=()
CLEANUP_SUPPLIER_IDS=()
CLEANUP_CONV_IDS=()

check() {
  local label="$1" expect="$2" method="$3" path="$4"; shift 4
  local code
  code=$(curl -s -o /tmp/qa_body.json -w "%{http_code}" -X "$method" "$BASE$path" "$@" 2>/dev/null)
  if [ "$code" = "$expect" ]; then PASS=$((PASS+1))
  else FAIL=$((FAIL+1)); echo "FAIL: $label — expected $expect got $code"; fi
}

check_field() {
  local label="$1" expr="$2" expected="$3"
  local actual
  actual=$(jq -r "$expr" /tmp/qa_body.json 2>/dev/null)
  if [ "$actual" = "$expected" ]; then PASS=$((PASS+1))
  else FAIL=$((FAIL+1)); echo "FAIL: $label — expected '$expected' got '$actual'"; fi
}

check_field_contains() {
  local label="$1" expr="$2" expected="$3"
  local actual
  actual=$(jq -r "$expr" /tmp/qa_body.json 2>/dev/null)
  if echo "$actual" | grep -q "$expected" 2>/dev/null; then PASS=$((PASS+1))
  else FAIL=$((FAIL+1)); echo "FAIL: $label — expected contains '$expected' got '$actual'"; fi
}

check_field_gt() {
  local label="$1" expr="$2" threshold="$3"
  local actual
  actual=$(jq -r "$expr" /tmp/qa_body.json 2>/dev/null)
  if [ "$(echo "$actual > $threshold" | bc 2>/dev/null)" = "1" ]; then PASS=$((PASS+1))
  else FAIL=$((FAIL+1)); echo "FAIL: $label — expected > $threshold got '$actual'"; fi
}

id_from_body() { jq -r '.id // .userId // .prodId // .categoryId // .petId // .serviceId // .storeId // .appointmentId // .adoptionId // .saleId // .couponId // .supId // empty' /tmp/qa_body.json 2>/dev/null; }

echo "========================================="
echo " PET SHOP QA — Full Backend Test Suite"
echo "========================================="

echo "--- 1. AUTH ---"

check "Admin login" 200 POST "/auth/login" -H 'Content-Type: application/json' -d '{"username":"admin","password":"admin123"}'
ADMIN_TOKEN=$(jq -r '.token' /tmp/qa_body.json)
if [ "$ADMIN_TOKEN" = "null" ] || [ -z "$ADMIN_TOKEN" ]; then echo "FATAL: Admin login failed"; exit 1; fi

check "Staff login" 200 POST "/auth/login" -H 'Content-Type: application/json' -d '{"username":"staff","password":"staff123"}'
STAFF_TOKEN=$(jq -r '.token' /tmp/qa_body.json)
if [ "$STAFF_TOKEN" = "null" ] || [ -z "$STAFF_TOKEN" ]; then echo "FATAL: Staff login failed"; exit 1; fi

check "Customer login" 200 POST "/auth/login" -H 'Content-Type: application/json' -d '{"username":"customer","password":"customer123"}'
CUST_TOKEN=$(jq -r '.token' /tmp/qa_body.json)
if [ "$CUST_TOKEN" = "null" ] || [ -z "$CUST_TOKEN" ]; then echo "FATAL: Customer login failed"; exit 1; fi

A=(-H "Authorization: Bearer $ADMIN_TOKEN")
S=(-H "Authorization: Bearer $STAFF_TOKEN")
C=(-H "Authorization: Bearer $CUST_TOKEN")
J=(-H "Content-Type: application/json")

check "GET /auth/me admin" 200 GET "/auth/me" "${A[@]}"
check_field "Admin role" ".role" "ADMIN"
check "GET /auth/me staff" 200 GET "/auth/me" "${S[@]}"
check_field "Staff role" ".role" "STAFF"
check "GET /auth/me customer" 200 GET "/auth/me" "${C[@]}"
check_field "Customer role" ".role" "CUSTOMER"

check "Admin avatar file" 200 GET "/auth/me/avatar/file" "${A[@]}"
check "Wrong password" 401 POST "/auth/login" "${J[@]}" -d '{"username":"admin","password":"wrong"}'
check "Empty login body" 400 POST "/auth/login" "${J[@]}" -d '{}'

check "Register QA user" 201 POST "/auth/register" "${J[@]}" -d '{"username":"testuser_qa","password":"Test1234!","email":"qa@test.com","firstName":"QA","lastName":"Test","phone":"5551234567"}'
QA_USER_ID=$(id_from_body)
[ -n "$QA_USER_ID" ] && CLEANUP_USER_IDS+=("$QA_USER_ID")

check "Login QA user" 200 POST "/auth/login" "${J[@]}" -d '{"username":"testuser_qa","password":"Test1234!"}'
QA_TOKEN=$(jq -r '.token' /tmp/qa_body.json)
check "GET /me QA user" 200 GET "/auth/me" -H "Authorization: Bearer $QA_TOKEN"
check_field "QA username" ".username" "testuser_qa"

check "Duplicate register" 409 POST "/auth/register" "${J[@]}" -d '{"username":"admin","password":"Test1234!","email":"dup@test.com","firstName":"A","lastName":"B","phone":"5550000000"}'
if [ "$(jq -r '.status // empty' /tmp/qa_body.json 2>/dev/null)" != "" ]; then PASS=$((PASS)); else
  check "Duplicate register alt" 400 POST "/auth/register" "${J[@]}" -d '{"username":"admin","password":"Test1234!","email":"dup2@test.com","firstName":"A","lastName":"B","phone":"5550000001"}'
fi
check "Register missing fields" 400 POST "/auth/register" "${J[@]}" -d '{"username":"incomplete_qa"}'

echo "--- 2. PRODUCTS ---"

check "GET /products" 200 GET "/products"
check "GET /products/1" 200 GET "/products/1"
check "GET /products?q=dog" 200 GET "/products?q=dog"
check "GET /products?categoryId=1" 200 GET "/products?categoryId=1"
check "GET /products/999999" 404 GET "/products/999999"

check "Create product (admin)" 201 POST "/products" "${A[@]}" "${J[@]}" -d '{"prodName":"QA_TEST_Product","prodDesc":"QA test","prodPrice":9.99,"categoryId":1}'
PROD_ID=$(id_from_body)
[ -n "$PROD_ID" ] && CLEANUP_PRODUCT_IDS+=("$PROD_ID")
check_field "Product name" ".prodName" "QA_TEST_Product"

check "Create product (customer)" 403 POST "/products" "${C[@]}" "${J[@]}" -d '{"prodName":"QA_TEST_Nope","prodPrice":1,"categoryId":1}'
check "Create product (no auth)" 401 POST "/products" "${J[@]}" -d '{"prodName":"QA_TEST_Nope2","prodPrice":1,"categoryId":1}'
check "Create product missing name" 400 POST "/products" "${A[@]}" "${J[@]}" -d '{"prodPrice":1,"categoryId":1}'

if [ -n "$PROD_ID" ]; then
  check "Update product" 200 PUT "/products/$PROD_ID" "${A[@]}" "${J[@]}" -d "{\"prodName\":\"QA_TEST_Updated\",\"prodDesc\":\"updated\",\"prodPrice\":19.99,\"categoryId\":1}"
  check_field "Updated name" ".prodName" "QA_TEST_Updated"
fi

check "Create product to delete" 201 POST "/products" "${A[@]}" "${J[@]}" -d '{"prodName":"QA_TEST_DeleteMe","prodDesc":"del","prodPrice":1,"categoryId":1}'
DEL_PROD_ID=$(id_from_body)
if [ -n "$DEL_PROD_ID" ]; then
  check "Delete product" 200 DELETE "/products/$DEL_PROD_ID" "${A[@]}"
  check "GET deleted product" 404 GET "/products/$DEL_PROD_ID"
fi

check "GET /products paginated" 200 GET "/products?page=0&size=5"
check "GET /products sorted" 200 GET "/products?sort=prodName,asc"

echo "--- 3. CATEGORIES ---"

check "GET /categories" 200 GET "/categories"
check "GET /categories/1" 200 GET "/categories/1"
check "GET /categories/999999" 404 GET "/categories/999999"

check "Create category (admin)" 201 POST "/categories" "${A[@]}" "${J[@]}" -d '{"categoryName":"QA_TEST_Category","categoryType":"qa"}'
CAT_ID=$(id_from_body)
[ -n "$CAT_ID" ] && CLEANUP_CATEGORY_IDS+=("$CAT_ID")

check "Create category (customer)" 403 POST "/categories" "${C[@]}" "${J[@]}" -d '{"categoryName":"QA_TEST_Nope"}'
check "Create category missing name" 400 POST "/categories" "${A[@]}" "${J[@]}" -d '{"categoryType":"no name"}'

if [ -n "$CAT_ID" ]; then
  check "Update category" 200 PUT "/categories/$CAT_ID" "${A[@]}" "${J[@]}" -d "{\"categoryName\":\"QA_TEST_CatUpdated\",\"categoryType\":\"updated\"}"
  check_field "Updated cat name" ".categoryName" "QA_TEST_CatUpdated"
fi

check "Create category to delete" 201 POST "/categories" "${A[@]}" "${J[@]}" -d '{"categoryName":"QA_TEST_CatDel","categoryType":"del"}'
DEL_CAT_ID=$(id_from_body)
if [ -n "$DEL_CAT_ID" ]; then
  check "Delete category" 200 DELETE "/categories/$DEL_CAT_ID" "${A[@]}"
  check "GET deleted category" 404 GET "/categories/$DEL_CAT_ID"
fi

echo "--- 4. PETS ---"

check "GET /pets" 200 GET "/pets"
check "GET /pets/2" 200 GET "/pets/2"
check "GET /pets?species=Dog" 200 GET "/pets?species=Dog"
check "GET /pets?status=Available" 200 GET "/pets?status=Available"
check "GET /pets/999999" 404 GET "/pets/999999"
check "GET /my-pets (customer)" 200 GET "/my-pets" "${C[@]}"

check "Admin create pet" 201 POST "/pets" "${A[@]}" "${J[@]}" -d '{"petName":"QA_TEST_Pet","petSpecies":"Dog","petBreed":"Labrador","petAge":2,"petStatus":"Available","storeId":1,"petPrice":100}'
PET_ID=$(id_from_body)
[ -n "$PET_ID" ] && CLEANUP_PET_IDS+=("$PET_ID")
check_field "Pet name" ".petName" "QA_TEST_Pet"
check_field "Pet species" ".petSpecies" "Dog"

if [ -n "$PET_ID" ]; then
  check "Update pet" 200 PUT "/pets/$PET_ID" "${A[@]}" "${J[@]}" -d "{\"petName\":\"QA_TEST_PetUpd\",\"petSpecies\":\"Dog\",\"petBreed\":\"Labrador\",\"petAge\":3,\"petStatus\":\"Available\",\"storeId\":1,\"petPrice\":150}"
  check_field "Updated pet name" ".petName" "QA_TEST_PetUpd"
fi

check "Admin create pet to delete" 201 POST "/pets" "${A[@]}" "${J[@]}" -d '{"petName":"QA_TEST_PetDel","petSpecies":"Cat","petBreed":"Siamese","petAge":1,"petStatus":"Available","storeId":1,"petPrice":50}'
DEL_PET_ID=$(id_from_body)
if [ -n "$DEL_PET_ID" ]; then
  check "Delete pet" 200 DELETE "/pets/$DEL_PET_ID" "${A[@]}"
  check "GET deleted pet" 404 GET "/pets/$DEL_PET_ID"
fi

check "Customer create my-pet" 201 POST "/my-pets" "${C[@]}" "${J[@]}" -d '{"petName":"QA_TEST_MyPet","species":"Rabbit","breed":"Holland Lop","petAge":1}'
MY_PET_ID=$(id_from_body)
[ -n "$MY_PET_ID" ] && CLEANUP_MYPET_IDS+=("$MY_PET_ID")
check "GET /my-pets has new pet" 200 GET "/my-pets" "${C[@]}"

check "Create pet (customer direct)" 403 POST "/pets" "${C[@]}" "${J[@]}" -d '{"petName":"QA_TEST_Nope","petSpecies":"Dog","petBreed":"Lab","petAge":1,"petStatus":"Available","storeId":1,"petPrice":10}'
check "Create pet (no auth)" 401 POST "/pets" "${J[@]}" -d '{"petName":"QA_TEST_Nope2","petSpecies":"Dog","petBreed":"Lab","petAge":1,"petStatus":"Available","storeId":1,"petPrice":10}'
check "GET /pets paginated" 200 GET "/pets?page=0&size=5"

echo "--- 5. SERVICES ---"

check "GET /services" 200 GET "/services"
check "GET /services/1" 200 GET "/services/1"
check "GET /services?species=Dog" 200 GET "/services?species=Dog"
check "GET /services/999999" 404 GET "/services/999999"

check "Create service (admin)" 201 POST "/services" "${A[@]}" "${J[@]}" -d '{"serviceName":"QA_TEST_Service","serviceDesc":"qa svc","servicePrice":25.00,"serviceDuration":30,"species":["Dog","Cat"]}'
SVC_ID=$(id_from_body)
[ -n "$SVC_ID" ] && CLEANUP_SERVICE_IDS+=("$SVC_ID")
check_field "Service name" ".serviceName" "QA_TEST_Service"

if [ -n "$SVC_ID" ]; then
  check "Update service" 200 PUT "/services/$SVC_ID" "${A[@]}" "${J[@]}" -d "{\"serviceName\":\"QA_TEST_SvcUpd\",\"serviceDesc\":\"upd\",\"servicePrice\":30,\"serviceDuration\":45,\"species\":[\"Dog\"]}"
fi

check "Create service to delete" 201 POST "/services" "${A[@]}" "${J[@]}" -d '{"serviceName":"QA_TEST_SvcDel","serviceDesc":"del","servicePrice":10,"serviceDuration":15,"species":["Cat"]}'
DEL_SVC_ID=$(id_from_body)
if [ -n "$DEL_SVC_ID" ]; then
  check "Delete service" 200 DELETE "/services/$DEL_SVC_ID" "${A[@]}"
fi
check "Create service (customer)" 403 POST "/services" "${C[@]}" "${J[@]}" -d '{"serviceName":"QA_TEST_Nope","servicePrice":10,"serviceDuration":10,"species":["Dog"]}'

echo "--- 6. STORES ---"

check "GET /stores" 200 GET "/stores"
check "GET /stores/1" 200 GET "/stores/1"
check "GET /stores/999999" 404 GET "/stores/999999"

check "Create store (admin)" 201 POST "/stores" "${A[@]}" "${J[@]}" -d '{"storeName":"QA_TEST_Store","address":"123 QA St","phone":"5559999999","email":"qastore@test.com"}'
STORE_ID=$(id_from_body)
[ -n "$STORE_ID" ] && CLEANUP_STORE_IDS+=("$STORE_ID")

if [ -n "$STORE_ID" ]; then
  check "Update store" 200 PUT "/stores/$STORE_ID" "${A[@]}" "${J[@]}" -d "{\"storeName\":\"QA_TEST_StoreUpd\",\"address\":\"456 QA Ave\",\"phone\":\"5559999998\",\"email\":\"qastoreupd@test.com\"}"
fi

check "Create store to delete" 201 POST "/stores" "${A[@]}" "${J[@]}" -d '{"storeName":"QA_TEST_StoreDel","address":"789 Del Rd","phone":"5559999997","email":"qastoredel@test.com"}'
DEL_STORE_ID=$(id_from_body)
if [ -n "$DEL_STORE_ID" ]; then
  check "Delete store" 200 DELETE "/stores/$DEL_STORE_ID" "${A[@]}"
fi

check "Create store (staff)" 403 POST "/stores" "${S[@]}" "${J[@]}" -d '{"storeName":"QA_TEST_Nope","address":"x","phone":"x","email":"x@x.com"}'

echo "--- 7. USERS / EMPLOYEES / CUSTOMERS ---"

check "GET /users (admin)" 200 GET "/users" "${A[@]}"
check "GET /users (customer)" 403 GET "/users" "${C[@]}"
check "GET /users/1" 200 GET "/users/1" "${A[@]}"
check "GET /users/999999" 404 GET "/users/999999" "${A[@]}"

check "GET /employees (admin)" 200 GET "/employees" "${A[@]}"
check "GET /employees (staff)" 403 GET "/employees" "${S[@]}"
check "GET /customers (staff)" 200 GET "/customers" "${S[@]}"
check "GET /customers (customer)" 403 GET "/customers" "${C[@]}"

check "Admin create user" 201 POST "/users" "${A[@]}" "${J[@]}" -d '{"username":"qa_test_user2","password":"Test1234!","email":"qa2@test.com","firstName":"QA2","lastName":"Test2","phone":"5552222222","role":"CUSTOMER"}'
NEW_USER_ID=$(id_from_body)
[ -n "$NEW_USER_ID" ] && CLEANUP_USER_IDS+=("$NEW_USER_ID")
check_field "Created username" ".username" "qa_test_user2"

if [ -n "$NEW_USER_ID" ]; then
  check "Update user" 200 PUT "/users/$NEW_USER_ID" "${A[@]}" "${J[@]}" -d "{\"username\":\"qa_test_user2\",\"email\":\"qa2upd@test.com\",\"firstName\":\"QA2U\",\"lastName\":\"Test2U\",\"phone\":\"5552222223\",\"role\":\"CUSTOMER\"}"
fi

check "GET /users/1/avatar/file" 200 GET "/users/1/avatar/file" "${A[@]}"
check "GET /users/50/avatar/file (default)" 200 GET "/users/50/avatar/file" "${A[@]}"

check "GET /users no auth" 401 GET "/users"
check "Create user (staff)" 403 POST "/users" "${S[@]}" "${J[@]}" -d '{"username":"qa_nope","password":"x","email":"n@n.com","firstName":"N","lastName":"N","phone":"0","role":"CUSTOMER"}'
check "Create user (customer)" 403 POST "/users" "${C[@]}" "${J[@]}" -d '{"username":"qa_nope2","password":"x","email":"n2@n.com","firstName":"N","lastName":"N","phone":"0","role":"CUSTOMER"}'

echo "--- 8. APPOINTMENTS ---"

check "GET /appointments (admin)" 200 GET "/appointments" "${A[@]}"
check "GET /appointments/1" 200 GET "/appointments/1" "${A[@]}"
check "GET /appointments?storeId=1" 200 GET "/appointments?storeId=1" "${A[@]}"
check "GET /appointments?status=Scheduled" 200 GET "/appointments?status=Scheduled" "${A[@]}"
check "GET /appointments/availability" 200 GET "/appointments/availability?storeId=1&serviceId=1&date=2027-06-01" "${A[@]}"
check "GET /appointments/999999" 404 GET "/appointments/999999" "${A[@]}"

check "Create appointment" 201 POST "/appointments" "${A[@]}" "${J[@]}" -d '{"petId":53,"customerId":32,"storeId":2,"employeeId":7,"serviceId":1,"appointmentDate":"2027-06-15","appointmentTime":"10:00","appointmentStatus":"Scheduled"}'
APPT_ID=$(id_from_body)
[ -n "$APPT_ID" ] && CLEANUP_APPT_IDS+=("$APPT_ID")
check_field "Appointment status" ".appointmentStatus" "Scheduled"

if [ -n "$APPT_ID" ]; then
  check "Cancel appointment" 200 PUT "/appointments/$APPT_ID" "${A[@]}" "${J[@]}" -d "{\"petId\":53,\"customerId\":32,\"storeId\":2,\"employeeId\":7,\"serviceId\":1,\"appointmentDate\":\"2027-06-15\",\"appointmentTime\":\"10:00\",\"appointmentStatus\":\"Cancelled\"}"
  check_field "Cancelled status" ".appointmentStatus" "Cancelled"
fi

check "Create appointment to delete" 201 POST "/appointments" "${A[@]}" "${J[@]}" -d '{"petId":53,"customerId":32,"storeId":2,"employeeId":7,"serviceId":1,"appointmentDate":"2027-07-01","appointmentTime":"14:00","appointmentStatus":"Scheduled"}'
DEL_APPT_ID=$(id_from_body)
if [ -n "$DEL_APPT_ID" ]; then
  check "Delete appointment" 200 DELETE "/appointments/$DEL_APPT_ID" "${A[@]}"
fi

check "Appointment past date" 400 POST "/appointments" "${A[@]}" "${J[@]}" -d '{"petId":53,"customerId":32,"storeId":2,"employeeId":7,"serviceId":1,"appointmentDate":"2020-01-01","appointmentTime":"10:00","appointmentStatus":"Scheduled"}'

check "Pet-service mismatch" 400 POST "/appointments" "${A[@]}" "${J[@]}" -d '{"petId":38,"customerId":17,"storeId":1,"employeeId":4,"serviceId":1,"appointmentDate":"2027-08-01","appointmentTime":"10:00","appointmentStatus":"Scheduled"}'

check "Create appt for duplicate test" 201 POST "/appointments" "${A[@]}" "${J[@]}" -d '{"petId":53,"customerId":32,"storeId":2,"employeeId":7,"serviceId":1,"appointmentDate":"2027-09-01","appointmentTime":"09:00","appointmentStatus":"Scheduled"}'
DUP_APPT_ID=$(id_from_body)
[ -n "$DUP_APPT_ID" ] && CLEANUP_APPT_IDS+=("$DUP_APPT_ID")
check "Duplicate time/employee" 400 POST "/appointments" "${A[@]}" "${J[@]}" -d '{"petId":53,"customerId":32,"storeId":2,"employeeId":7,"serviceId":1,"appointmentDate":"2027-09-01","appointmentTime":"09:00","appointmentStatus":"Scheduled"}'

check "GET /appointments (customer)" 200 GET "/appointments" "${C[@]}"
check "GET /appointments (staff)" 200 GET "/appointments" "${S[@]}"
check "Create appointment (no auth)" 401 POST "/appointments" "${J[@]}" -d '{"petId":53,"customerId":32,"storeId":1,"employeeId":4,"serviceId":1,"appointmentDate":"2027-10-01","appointmentTime":"10:00","appointmentStatus":"Scheduled"}'

echo "--- 9. ADOPTIONS ---"

check "GET /adoptions (admin)" 200 GET "/adoptions" "${A[@]}"
check "GET /adoptions/1" 200 GET "/adoptions/1" "${A[@]}"
check "GET /adoptions/999999" 404 GET "/adoptions/999999" "${A[@]}"

AVAIL_PET_1=""
AVAIL_PET_2=""
AVAIL_PET_3=""
curl -s "$BASE/pets?status=Available&size=5" "${A[@]}" -o /tmp/qa_avail.json 2>/dev/null
AVAIL_PET_1=$(jq -r '.content[0].petId // empty' /tmp/qa_avail.json 2>/dev/null)
AVAIL_PET_2=$(jq -r '.content[1].petId // empty' /tmp/qa_avail.json 2>/dev/null)
AVAIL_PET_3=$(jq -r '.content[2].petId // empty' /tmp/qa_avail.json 2>/dev/null)

if [ -n "$AVAIL_PET_1" ]; then
  check "Staff create adoption (Pending)" 201 POST "/adoptions" "${S[@]}" "${J[@]}" -d "{\"petId\":$AVAIL_PET_1,\"customerId\":32,\"sourceStoreId\":1,\"adoptionDate\":\"2027-06-15\",\"adoptionStatus\":\"Pending\"}"
  ADOPT_ID_1=$(id_from_body)
  [ -n "$ADOPT_ID_1" ] && CLEANUP_ADOPTION_IDS+=("$ADOPT_ID_1")

  check "Pet now Pending" 200 GET "/pets/$AVAIL_PET_1"
  check_field "Pet status Pending" ".petStatus" "Pending"

  if [ -n "$ADOPT_ID_1" ]; then
    check "Cancel adoption" 200 PUT "/adoptions/$ADOPT_ID_1" "${S[@]}" "${J[@]}" -d "{\"petId\":$AVAIL_PET_1,\"customerId\":32,\"sourceStoreId\":1,\"adoptionDate\":\"2027-06-15\",\"adoptionStatus\":\"Cancelled\"}"
    check "Pet back to Available" 200 GET "/pets/$AVAIL_PET_1"
    check_field "Pet status Available" ".petStatus" "Available"
  fi
fi

if [ -n "$AVAIL_PET_2" ]; then
  check "Staff create adoption 2" 201 POST "/adoptions" "${S[@]}" "${J[@]}" -d "{\"petId\":$AVAIL_PET_2,\"customerId\":33,\"sourceStoreId\":1,\"adoptionDate\":\"2027-06-15\",\"adoptionStatus\":\"Pending\"}"
  ADOPT_ID_2=$(id_from_body)
  [ -n "$ADOPT_ID_2" ] && CLEANUP_ADOPTION_IDS+=("$ADOPT_ID_2")

  if [ -n "$ADOPT_ID_2" ]; then
    check "Complete adoption" 200 PUT "/adoptions/$ADOPT_ID_2" "${S[@]}" "${J[@]}" -d "{\"petId\":$AVAIL_PET_2,\"customerId\":33,\"sourceStoreId\":1,\"adoptionDate\":\"2027-06-15\",\"adoptionStatus\":\"Completed\"}"
    check "Pet now Adopted" 200 GET "/pets/$AVAIL_PET_2"
    check_field "Pet status Adopted" ".petStatus" "Adopted"
  fi
fi

if [ -n "$AVAIL_PET_3" ]; then
  check "Customer request adoption" 201 POST "/adoptions" "${C[@]}" "${J[@]}" -d "{\"petId\":$AVAIL_PET_3,\"sourceStoreId\":1,\"adoptionDate\":\"2027-06-15\"}"
  ADOPT_ID_3=$(id_from_body)
  [ -n "$ADOPT_ID_3" ] && CLEANUP_ADOPTION_IDS+=("$ADOPT_ID_3")

  if [ -n "$ADOPT_ID_3" ]; then
    check "Cancel customer adoption" 200 PUT "/adoptions/$ADOPT_ID_3" "${C[@]}" "${J[@]}" -d "{\"petId\":$AVAIL_PET_3,\"sourceStoreId\":1,\"adoptionDate\":\"2027-06-15\",\"adoptionStatus\":\"Cancelled\"}"
    check "Pet Available again" 200 GET "/pets/$AVAIL_PET_3"
    check_field "Pet Available after cancel" ".petStatus" "Available"
  fi

  check "Adopt already pending" 201 POST "/adoptions" "${S[@]}" "${J[@]}" -d "{\"petId\":$AVAIL_PET_3,\"customerId\":34,\"sourceStoreId\":1,\"adoptionDate\":\"2027-06-15\",\"adoptionStatus\":\"Pending\"}"
  ADOPT_BLOCK_ID=$(id_from_body)
  [ -n "$ADOPT_BLOCK_ID" ] && CLEANUP_ADOPTION_IDS+=("$ADOPT_BLOCK_ID")
  check "Duplicate adoption for pending pet" 400 POST "/adoptions" "${S[@]}" "${J[@]}" -d "{\"petId\":$AVAIL_PET_3,\"customerId\":35,\"sourceStoreId\":1,\"adoptionDate\":\"2027-06-15\",\"adoptionStatus\":\"Pending\"}"
fi

check "GET /adoptions (staff)" 200 GET "/adoptions" "${S[@]}"
check "GET /adoptions (customer)" 200 GET "/adoptions" "${C[@]}"

echo "--- 10. SALES ---"

check "GET /sales (admin)" 200 GET "/sales" "${A[@]}"
check "GET /sales/1" 200 GET "/sales/1" "${A[@]}"
check "GET /sales/my (customer)" 200 GET "/sales/my" "${C[@]}"
check "GET /sales (customer)" 403 GET "/sales" "${C[@]}"
check "GET /sales/999999" 404 GET "/sales/999999" "${A[@]}"

curl -s "$BASE/inventory?storeId=1" "${A[@]}" -o /tmp/qa_inv_before.json 2>/dev/null
INV_BEFORE=$(jq -r '.content[] | select(.prodId == 1) | .quantity // 0' /tmp/qa_inv_before.json 2>/dev/null | head -1)

check "Staff create sale" 201 POST "/sales" "${S[@]}" "${J[@]}" -d '{"storeId":1,"customerId":32,"items":[{"prodId":1,"quantity":1}]}'
SALE_ID=$(id_from_body)
[ -n "$SALE_ID" ] && CLEANUP_SALE_IDS+=("$SALE_ID")

if [ -n "$INV_BEFORE" ] && [ "$INV_BEFORE" != "" ] && [ "$INV_BEFORE" != "null" ]; then
  curl -s "$BASE/inventory?storeId=1" "${A[@]}" -o /tmp/qa_inv_after.json 2>/dev/null
  INV_AFTER=$(jq -r '.content[] | select(.prodId == 1) | .quantity // 0' /tmp/qa_inv_after.json 2>/dev/null | head -1)
  if [ -n "$INV_AFTER" ] && [ "$INV_AFTER" != "null" ] && [ "$((INV_BEFORE - 1))" = "$INV_AFTER" ]; then
    PASS=$((PASS+1))
  else
    FAIL=$((FAIL+1)); echo "FAIL: Inventory decrease — before=$INV_BEFORE after=$INV_AFTER"
  fi
fi

check "Sale non-existent product" 404 POST "/sales" "${S[@]}" "${J[@]}" -d '{"storeId":1,"customerId":32,"items":[{"prodId":999999,"quantity":1}]}'
check "Sale zero quantity" 400 POST "/sales" "${S[@]}" "${J[@]}" -d '{"storeId":1,"customerId":32,"items":[{"prodId":1,"quantity":0}]}'
check "Sale (no auth)" 401 POST "/sales" "${J[@]}" -d '{"storeId":1,"customerId":32,"items":[{"prodId":1,"quantity":1}]}'
check "Sale (customer)" 403 POST "/sales" "${C[@]}" "${J[@]}" -d '{"storeId":1,"customerId":15,"items":[{"prodId":1,"quantity":1}]}'

check "Staff create sale 2" 201 POST "/sales" "${S[@]}" "${J[@]}" -d '{"storeId":1,"customerId":32,"items":[{"prodId":2,"quantity":1}]}'
SALE_ID_2=$(id_from_body)
[ -n "$SALE_ID_2" ] && CLEANUP_SALE_IDS+=("$SALE_ID_2")

check "GET /sales filtered by store" 200 GET "/sales?storeId=1" "${A[@]}"
check "GET /sales paginated" 200 GET "/sales?page=0&size=5" "${A[@]}"

echo "--- 11. CART ---"

check "GET /cart (customer)" 200 GET "/cart?storeId=1" "${C[@]}"

check "Add cart item" 200 POST "/cart/add" "${C[@]}" "${J[@]}" -d '{"prodId":1,"storeId":1,"quantity":1}'
if [ "$(jq -r '.cartStatus // empty' /tmp/qa_body.json 2>/dev/null)" = "" ]; then
  check "Add cart item alt" 200 POST "/cart/add" "${C[@]}" "${J[@]}" -d '{"prodId":2,"storeId":1,"quantity":1}'
fi

check "GET cart with item" 200 GET "/cart?storeId=1" "${C[@]}"
CART_SUBTOTAL=$(jq -r '.subtotalAmount // 0' /tmp/qa_body.json 2>/dev/null)
CART_ITEM_ID=$(jq -r '.items[0].cartItemId // empty' /tmp/qa_body.json 2>/dev/null)

if [ -n "$CART_ITEM_ID" ]; then
  check "Update cart qty" 200 PUT "/cart/update" "${C[@]}" "${J[@]}" -d "{\"cartItemId\":$CART_ITEM_ID,\"quantity\":2}"
  check "GET cart after qty update" 200 GET "/cart?storeId=1" "${C[@]}"
fi

check "Apply coupon WELCOME10" 200 POST "/cart/apply-coupon?storeId=1" "${C[@]}" "${J[@]}" -d '{"couponCode":"WELCOME10"}'
check "GET cart with coupon" 200 GET "/cart?storeId=1" "${C[@]}"
DISCOUNT=$(jq -r '.discountAmount // 0' /tmp/qa_body.json 2>/dev/null)

check "Remove coupon" 200 DELETE "/cart/coupon?storeId=1" "${C[@]}" "${J[@]}"
check "GET cart no coupon" 200 GET "/cart?storeId=1" "${C[@]}"

check "Apply points" 200 POST "/cart/apply-points?storeId=1&useLoyaltyPoints=true" "${C[@]}" "${J[@]}"
check "Remove points" 200 POST "/cart/apply-points?storeId=1&useLoyaltyPoints=false" "${C[@]}" "${J[@]}"

if [ -n "$CART_ITEM_ID" ]; then
  check "Remove cart item" 200 DELETE "/cart/remove/$CART_ITEM_ID" "${C[@]}"
fi

check "Clear cart" 204 DELETE "/cart/clear?storeId=1" "${C[@]}"

check "Add item qty 0" 400 POST "/cart/add" "${C[@]}" "${J[@]}" -d '{"prodId":1,"storeId":1,"quantity":0}'
check "Apply invalid coupon" 400 POST "/cart/apply-coupon?storeId=1" "${C[@]}" "${J[@]}" -d '{"couponCode":"FAKECOUPON999"}'
check "Checkout empty cart" 400 POST "/cart/checkout" "${C[@]}" "${J[@]}" -d '{"storeId":1}'

check "Add item for checkout test" 200 POST "/cart/add" "${C[@]}" "${J[@]}" -d '{"prodId":1,"storeId":1,"quantity":1}'
check "Checkout" 200 POST "/cart/checkout" "${C[@]}" "${J[@]}" -d '{"storeId":1}'
CHECKOUT_SALE_ID=$(jq -r '.cartId // empty' /tmp/qa_body.json 2>/dev/null)
[ -n "$CHECKOUT_SALE_ID" ] && CLEANUP_SALE_IDS+=("$CHECKOUT_SALE_ID")

check "Clear cart final" 204 DELETE "/cart/clear?storeId=1" "${C[@]}"

echo "--- 12. REFUNDS ---"

check "GET /refunds (admin)" 200 GET "/refunds" "${A[@]}"
check "GET /refunds (customer)" 200 GET "/refunds" "${C[@]}"

CUST_SALE_ID=""
if [ -n "$CHECKOUT_SALE_ID" ]; then
  CUST_SALE_ID="$CHECKOUT_SALE_ID"
else
  curl -s "$BASE/sales/my" "${C[@]}" -o /tmp/qa_my_sales.json 2>/dev/null
  CUST_SALE_ID=$(jq -r '.content[0].saleId // .[0].saleId // empty' /tmp/qa_my_sales.json 2>/dev/null)
fi

if [ -n "$CUST_SALE_ID" ]; then
  check "Customer create refund" 201 POST "/refunds" "${C[@]}" "${J[@]}" -d "{\"saleId\":$CUST_SALE_ID,\"reason\":\"QA_TEST refund reason\",\"items\":[{\"prodId\":1,\"quantity\":1}]}"
  REFUND_ID=$(id_from_body)

  if [ -n "$REFUND_ID" ]; then
    check "Staff approve refund" 200 PUT "/refunds/$REFUND_ID" "${S[@]}" "${J[@]}" -d '{"status":"Approved"}'
    check_field "Refund approved" ".status" "Approved"
  fi
fi

check "Refund non-existent sale" 404 POST "/refunds" "${C[@]}" "${J[@]}" -d '{"saleId":999999,"reason":"QA_TEST nope","items":[{"prodId":1,"quantity":1}]}'
check "Refund missing reason" 400 POST "/refunds" "${C[@]}" "${J[@]}" -d '{"saleId":1,"items":[{"prodId":1,"quantity":1}]}'
check "GET /refunds (staff)" 200 GET "/refunds" "${S[@]}"
check "GET /refunds paginated" 200 GET "/refunds?page=0&size=5" "${A[@]}"

echo "--- 13. COUPONS ---"

check "GET /coupons (admin)" 200 GET "/coupons" "${A[@]}"
check "GET /coupons/1" 200 GET "/coupons/1" "${A[@]}"
check "GET /coupons/code/WELCOME10" 200 GET "/coupons/code/WELCOME10" "${A[@]}"
check "GET /coupons (customer)" 403 GET "/coupons" "${C[@]}"

check "Create coupon" 201 POST "/coupons" "${A[@]}" "${J[@]}" -d '{"couponCode":"QA_TEST_CPN","discountType":"PERCENTAGE","discountValue":10,"usageLimit":100}'
CPN_ID=$(id_from_body)
[ -n "$CPN_ID" ] && CLEANUP_COUPON_IDS+=("$CPN_ID")
check_field "Coupon code" ".couponCode" "QA_TEST_CPN"

if [ -n "$CPN_ID" ]; then
  check "Update coupon" 200 PUT "/coupons/$CPN_ID" "${A[@]}" "${J[@]}" -d "{\"couponCode\":\"QA_TEST_CPN\",\"discountType\":\"PERCENTAGE\",\"discountValue\":15,\"usageLimit\":50}"
fi

check "Create coupon to delete" 201 POST "/coupons" "${A[@]}" "${J[@]}" -d '{"couponCode":"QA_TEST_DEL","discountType":"PERCENTAGE","discountValue":5,"usageLimit":10}'
DEL_CPN_ID=$(id_from_body)
if [ -n "$DEL_CPN_ID" ]; then
  check "Delete coupon" 200 DELETE "/coupons/$DEL_CPN_ID" "${A[@]}"
fi

check "Coupon 100% discount" 400 POST "/coupons" "${A[@]}" "${J[@]}" -d '{"couponCode":"QA_TEST_100","discountType":"PERCENTAGE","discountValue":100,"usageLimit":1}'
check "Coupon 150% discount" 400 POST "/coupons" "${A[@]}" "${J[@]}" -d '{"couponCode":"QA_TEST_150","discountType":"PERCENTAGE","discountValue":150,"usageLimit":1}'

check "Coupon 99.99%" 201 POST "/coupons" "${A[@]}" "${J[@]}" -d '{"couponCode":"QA_TEST_99","discountType":"PERCENTAGE","discountValue":99.99,"usageLimit":1}'
BOUNDARY_CPN_ID=$(id_from_body)
[ -n "$BOUNDARY_CPN_ID" ] && CLEANUP_COUPON_IDS+=("$BOUNDARY_CPN_ID")

check "Duplicate coupon code" 400 POST "/coupons" "${A[@]}" "${J[@]}" -d '{"couponCode":"WELCOME10","discountType":"PERCENTAGE","discountValue":5,"usageLimit":1}'
check "Create coupon (customer)" 403 POST "/coupons" "${C[@]}" "${J[@]}" -d '{"couponCode":"QA_TEST_NOPE","discountType":"PERCENTAGE","discountValue":5,"usageLimit":1}'

echo "--- 14. SUPPLIERS / PRODUCT-SUPPLIERS / INVENTORY / PURCHASE-ORDERS ---"

check "GET /suppliers (admin)" 200 GET "/suppliers" "${A[@]}"
check "GET /suppliers/1" 200 GET "/suppliers/1" "${A[@]}"
check "GET /suppliers (customer)" 403 GET "/suppliers" "${C[@]}"

check "Create supplier" 201 POST "/suppliers" "${A[@]}" "${J[@]}" -d '{"supCompany":"QA_TEST_Supplier","supContactFirstName":"QA","supContactLastName":"Contact","supEmail":"qa_supplier@test.com","supPhone":"5553333333"}'
SUPP_ID=$(id_from_body)
[ -n "$SUPP_ID" ] && CLEANUP_SUPPLIER_IDS+=("$SUPP_ID")

if [ -n "$SUPP_ID" ]; then
  check "Update supplier" 200 PUT "/suppliers/$SUPP_ID" "${A[@]}" "${J[@]}" -d "{\"supCompany\":\"QA_TEST_SuppUpd\",\"supContactFirstName\":\"QA\",\"supContactLastName\":\"Updated\",\"supEmail\":\"qa_supp_upd@test.com\",\"supPhone\":\"5553333334\"}"
fi

check "Create supplier to delete" 201 POST "/suppliers" "${A[@]}" "${J[@]}" -d '{"supCompany":"QA_TEST_SuppDel","supContactFirstName":"Del","supContactLastName":"Test","supEmail":"del@test.com","supPhone":"5550000000"}'
DEL_SUPP_ID=$(id_from_body)
if [ -n "$DEL_SUPP_ID" ]; then
  check "Delete supplier" 200 DELETE "/suppliers/$DEL_SUPP_ID" "${A[@]}"
fi

check "GET /product-suppliers (admin)" 200 GET "/product-suppliers" "${A[@]}"
check "GET /inventory (admin)" 200 GET "/inventory" "${A[@]}"
check "GET /inventory/1" 200 GET "/inventory/1" "${A[@]}"
check "GET /purchase-orders (admin)" 200 GET "/purchase-orders" "${A[@]}"
check "GET /purchase-orders (customer)" 403 GET "/purchase-orders" "${C[@]}"
check "GET /inventory (customer)" 403 GET "/inventory" "${C[@]}"

echo "--- 15. CHAT ---"

check "GET /chat/conversations (customer)" 200 GET "/chat/conversations" "${C[@]}"

check "Create conversation" 201 POST "/chat/conversations" "${C[@]}" "${J[@]}" -d '{}'
CONV_ID=$(id_from_body)
[ -n "$CONV_ID" ] && CLEANUP_CONV_IDS+=("$CONV_ID")

if [ -n "$CONV_ID" ]; then
  check "Send message" 201 POST "/chat/conversations/$CONV_ID/messages" "${C[@]}" "${J[@]}" -d '{"content":"Hello from QA_TEST"}'

  check "Send empty message" 400 POST "/chat/conversations/$CONV_ID/messages" "${C[@]}" "${J[@]}" -d '{"content":""}'
  check "Send null content" 400 POST "/chat/conversations/$CONV_ID/messages" "${C[@]}" "${J[@]}" -d '{}'

  check "GET messages" 200 GET "/chat/conversations/$CONV_ID/messages" "${C[@]}"

  check "Request human takeover" 200 POST "/chat/conversations/$CONV_ID/request-human" "${C[@]}" "${J[@]}" -d '{}'

  check "Staff view conversations" 200 GET "/chat/conversations" "${S[@]}"

  check "Staff send reply" 201 POST "/chat/conversations/$CONV_ID/messages" "${S[@]}" "${J[@]}" -d '{"content":"Staff reply QA_TEST"}'

  check "GET conversation detail" 200 GET "/chat/conversations/$CONV_ID" "${S[@]}"

  check "Close conversation" 200 PUT "/chat/conversations/$CONV_ID" "${S[@]}" "${J[@]}" -d '{"status":"CLOSED"}'
  check "GET closed conversation" 200 GET "/chat/conversations/$CONV_ID" "${C[@]}"
  check_field "Conversation closed" ".status" "CLOSED"

  check "Send to closed" 400 POST "/chat/conversations/$CONV_ID/messages" "${C[@]}" "${J[@]}" -d '{"content":"should fail"}'
fi

check "GET /chat/conversations (admin)" 200 GET "/chat/conversations" "${A[@]}"
check "Create conv 2" 201 POST "/chat/conversations" "${C[@]}" "${J[@]}" -d '{}'
CONV_ID_2=$(id_from_body)
[ -n "$CONV_ID_2" ] && CLEANUP_CONV_IDS+=("$CONV_ID_2")
check "Send message conv 2" 201 POST "/chat/conversations/$CONV_ID_2/messages" "${C[@]}" "${J[@]}" -d '{"content":"QA_TEST second conv"}'

echo "--- 16. ACTIVITY LOGS / ANALYTICS / DROPDOWNS / HEALTH ---"

check "GET /health" 200 GET "/health"
check "GET /activity-logs (admin)" 200 GET "/activity-logs" "${A[@]}"
check "GET /activity-logs (customer)" 403 GET "/activity-logs" "${C[@]}"
check "GET /analytics/dashboard (admin)" 200 GET "/analytics/dashboard" "${A[@]}"
check "GET /analytics/dashboard (customer)" 403 GET "/analytics/dashboard" "${C[@]}"
check "GET /analytics/dashboard?days=1" 200 GET "/analytics/dashboard?days=1" "${A[@]}"

for ep in "dropdowns/pets" "dropdowns/services" "dropdowns/products" "dropdowns/categories" \
          "dropdowns/product-categories" "dropdowns/pet-species" "dropdowns/pet-breeds" \
          "dropdowns/stores" "dropdowns/customers" "dropdowns/adoption-pets" \
          "dropdowns/employees" "dropdowns/suppliers"; do
  check "GET /$ep" 200 GET "/$ep" "${A[@]}"
done

check "GET /dropdowns/stores/1/employees" 200 GET "/dropdowns/stores/1/employees" "${A[@]}"
check "GET /dropdowns/customers/32/pets" 200 GET "/dropdowns/customers/32/pets" "${A[@]}"

echo "--- 17. CROSS-ENTITY ---"

curl -s "$BASE/inventory?storeId=1" "${A[@]}" -o /tmp/qa_cross_inv1.json 2>/dev/null
CROSS_INV_BEFORE=$(jq -r '.content[] | select(.prodId == 2) | .quantity // 0' /tmp/qa_cross_inv1.json 2>/dev/null | head -1)

check "Cross: create sale" 201 POST "/sales" "${S[@]}" "${J[@]}" -d '{"storeId":1,"customerId":32,"items":[{"prodId":2,"quantity":1}]}'
CROSS_SALE_ID=$(id_from_body)
[ -n "$CROSS_SALE_ID" ] && CLEANUP_SALE_IDS+=("$CROSS_SALE_ID")

if [ -n "$CROSS_INV_BEFORE" ] && [ "$CROSS_INV_BEFORE" != "null" ] && [ "$CROSS_INV_BEFORE" != "" ]; then
  curl -s "$BASE/inventory?storeId=1" "${A[@]}" -o /tmp/qa_cross_inv2.json 2>/dev/null
  CROSS_INV_AFTER=$(jq -r '.content[] | select(.prodId == 2) | .quantity // 0' /tmp/qa_cross_inv2.json 2>/dev/null | head -1)
  if [ "$((CROSS_INV_BEFORE - 1))" = "$CROSS_INV_AFTER" ]; then
    PASS=$((PASS+1))
  else
    FAIL=$((FAIL+1)); echo "FAIL: Cross inventory decrease — before=$CROSS_INV_BEFORE after=$CROSS_INV_AFTER"
  fi
fi

if [ -n "$CROSS_SALE_ID" ]; then
  check "Cross: create refund" 201 POST "/refunds" "${C[@]}" "${J[@]}" -d "{\"saleId\":$CROSS_SALE_ID,\"reason\":\"QA_TEST cross refund\",\"items\":[{\"prodId\":2,\"quantity\":1}]}"
  CROSS_REFUND_ID=$(id_from_body)
  if [ -n "$CROSS_REFUND_ID" ]; then
    check "Cross: approve refund" 200 PUT "/refunds/$CROSS_REFUND_ID" "${S[@]}" "${J[@]}" -d '{"status":"Approved"}'
    curl -s "$BASE/inventory?storeId=1" "${A[@]}" -o /tmp/qa_cross_inv3.json 2>/dev/null
    CROSS_INV_RESTORED=$(jq -r '.content[] | select(.prodId == 2) | .quantity // 0' /tmp/qa_cross_inv3.json 2>/dev/null | head -1)
    if [ -n "$CROSS_INV_RESTORED" ] && [ "$CROSS_INV_RESTORED" = "$CROSS_INV_BEFORE" ]; then
      PASS=$((PASS+1))
    else
      FAIL=$((FAIL+1)); echo "FAIL: Cross inventory restore — expected=$CROSS_INV_BEFORE got=$CROSS_INV_RESTORED"
    fi
  fi
fi

curl -s "$BASE/pets?status=Available&size=5&page=1" "${A[@]}" -o /tmp/qa_cross_avail.json 2>/dev/null
CROSS_PET=$(jq -r '.content[0].petId // empty' /tmp/qa_cross_avail.json 2>/dev/null)

if [ -n "$CROSS_PET" ]; then
  check "Cross: create adoption Pending" 201 POST "/adoptions" "${S[@]}" "${J[@]}" -d "{\"petId\":$CROSS_PET,\"customerId\":35,\"sourceStoreId\":1,\"adoptionDate\":\"2027-06-15\",\"adoptionStatus\":\"Pending\"}"
  CROSS_ADOPT_ID=$(id_from_body)
  [ -n "$CROSS_ADOPT_ID" ] && CLEANUP_ADOPTION_IDS+=("$CROSS_ADOPT_ID")

  check "Cross: pet is Pending" 200 GET "/pets/$CROSS_PET"
  check_field "Cross pet Pending" ".petStatus" "Pending"

  if [ -n "$CROSS_ADOPT_ID" ]; then
    check "Cross: complete adoption" 200 PUT "/adoptions/$CROSS_ADOPT_ID" "${S[@]}" "${J[@]}" -d "{\"petId\":$CROSS_PET,\"customerId\":35,\"sourceStoreId\":1,\"adoptionDate\":\"2027-06-15\",\"adoptionStatus\":\"Completed\"}"
    check "Cross: pet is Adopted" 200 GET "/pets/$CROSS_PET"
    check_field "Cross pet Adopted" ".petStatus" "Adopted"
  fi
fi

curl -s "$BASE/pets?status=Available&size=5&page=2" "${A[@]}" -o /tmp/qa_cross_avail2.json 2>/dev/null
CROSS_PET_2=$(jq -r '.content[0].petId // empty' /tmp/qa_cross_avail2.json 2>/dev/null)

if [ -n "$CROSS_PET_2" ]; then
  check "Cross: adopt then cancel" 201 POST "/adoptions" "${S[@]}" "${J[@]}" -d "{\"petId\":$CROSS_PET_2,\"customerId\":36,\"sourceStoreId\":1,\"adoptionDate\":\"2027-06-15\",\"adoptionStatus\":\"Pending\"}"
  CROSS_ADOPT_ID_2=$(id_from_body)
  [ -n "$CROSS_ADOPT_ID_2" ] && CLEANUP_ADOPTION_IDS+=("$CROSS_ADOPT_ID_2")

  if [ -n "$CROSS_ADOPT_ID_2" ]; then
    check "Cross: cancel adoption" 200 PUT "/adoptions/$CROSS_ADOPT_ID_2" "${S[@]}" "${J[@]}" -d "{\"petId\":$CROSS_PET_2,\"customerId\":36,\"sourceStoreId\":1,\"adoptionDate\":\"2027-06-15\",\"adoptionStatus\":\"Cancelled\"}"
    check "Cross: pet Available" 200 GET "/pets/$CROSS_PET_2"
    check_field "Cross pet Available" ".petStatus" "Available"
  fi
fi

echo ""
echo "--- CLEANUP ---"

for id in "${CLEANUP_CONV_IDS[@]}"; do
  curl -s -o /dev/null -X PUT "$BASE/chat/conversations/$id" "${S[@]}" "${J[@]}" -d '{"status":"CLOSED"}' 2>/dev/null
done

for id in "${CLEANUP_ADOPTION_IDS[@]}"; do
  curl -s -o /dev/null -X DELETE "$BASE/adoptions/$id" "${A[@]}" 2>/dev/null
done

for id in "${CLEANUP_APPT_IDS[@]}"; do
  curl -s -o /dev/null -X DELETE "$BASE/appointments/$id" "${A[@]}" 2>/dev/null
done

for id in "${CLEANUP_SALE_IDS[@]}"; do
  curl -s -o /dev/null -X DELETE "$BASE/sales/$id" "${A[@]}" 2>/dev/null
done

for id in "${CLEANUP_MYPET_IDS[@]}"; do
  curl -s -o /dev/null -X DELETE "$BASE/my-pets/$id" "${C[@]}" 2>/dev/null
done

for id in "${CLEANUP_PET_IDS[@]}"; do
  curl -s -o /dev/null -X DELETE "$BASE/pets/$id" "${A[@]}" 2>/dev/null
done

for id in "${CLEANUP_SERVICE_IDS[@]}"; do
  curl -s -o /dev/null -X DELETE "$BASE/services/$id" "${A[@]}" 2>/dev/null
done

for id in "${CLEANUP_PRODUCT_IDS[@]}"; do
  curl -s -o /dev/null -X DELETE "$BASE/products/$id" "${A[@]}" 2>/dev/null
done

for id in "${CLEANUP_CATEGORY_IDS[@]}"; do
  curl -s -o /dev/null -X DELETE "$BASE/categories/$id" "${A[@]}" 2>/dev/null
done

for id in "${CLEANUP_STORE_IDS[@]}"; do
  curl -s -o /dev/null -X DELETE "$BASE/stores/$id" "${A[@]}" 2>/dev/null
done

for id in "${CLEANUP_COUPON_IDS[@]}"; do
  curl -s -o /dev/null -X DELETE "$BASE/coupons/$id" "${A[@]}" 2>/dev/null
done

for id in "${CLEANUP_SUPPLIER_IDS[@]}"; do
  curl -s -o /dev/null -X DELETE "$BASE/suppliers/$id" "${A[@]}" 2>/dev/null
done

for id in "${CLEANUP_USER_IDS[@]}"; do
  curl -s -o /dev/null -X DELETE "$BASE/users/$id" "${A[@]}" 2>/dev/null
done

curl -s -o /dev/null -X DELETE "$BASE/users" "${A[@]}" -G -d "username=testuser_qa" 2>/dev/null

rm -f /tmp/qa_body.json /tmp/qa_avail.json /tmp/qa_inv_before.json /tmp/qa_inv_after.json
rm -f /tmp/qa_my_sales.json /tmp/qa_cross_inv1.json /tmp/qa_cross_inv2.json /tmp/qa_cross_inv3.json
rm -f /tmp/qa_cross_avail.json /tmp/qa_cross_avail2.json

echo ""
echo "========================================="
echo "RESULTS: $PASS passed, $FAIL failed"
echo "========================================="
