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

: "${INTERNAL_API_TOKEN:?INTERNAL_API_TOKEN is required}"

base_url="${APP_TEST_URL:-http://127.0.0.1:3000}"
work_dir="$(mktemp -d)"
trap 'rm -rf "$work_dir"' EXIT
response_file="$work_dir/response.json"
auth_header="Authorization: Bearer $INTERNAL_API_TOKEN"
external_id="phase3-$(date +%s)"
chat_id="phase3-chat-$(date +%s)"

request() {
  local expected="$1"
  local name="$2"
  shift 2
  local status
  status="$(curl --silent --show-error --output "$response_file" --write-out '%{http_code}' "$@")"
  if [[ "$status" != "$expected" ]]; then
    echo "FAIL $name: expected $expected, got $status" >&2
    cat "$response_file" >&2
    exit 1
  fi
  echo "PASS $name ($status)"
}

request 200 "public health" "$base_url/api/health"
request 401 "internal authentication" "$base_url/api/internal/settings"
request 422 "invalid input" -X POST -H "$auth_header" -H 'Content-Type: application/json' \
  --data '{"phoneE164":"bad"}' "$base_url/api/internal/risk-context"

request 200 "settings" -H "$auth_header" "$base_url/api/internal/settings"
request 200 "stock" -H "$auth_header" "$base_url/api/internal/products/stock?skus=SKU-PROD-001,SKU-PROD-002"
request 200 "risk context" -X POST -H "$auth_header" -H 'Content-Type: application/json' \
  --data '{"phoneE164":"+201012345678","addressNormalized":"12 Test Street Cairo","name":"API Test","email":"api@example.com"}' \
  "$base_url/api/internal/risk-context"

order_payload="$(jq -n --arg externalId "$external_id" '{
  externalId: $externalId,
  source: "phase3-test",
  customer: {name: "API Test", phoneE164: "+201012345678", email: "api@example.com", country: "EG", telecomOperator: "Vodafone"},
  addressRaw: "12 Test Street, Nasr City, Cairo",
  addressLine: "12 Test Street",
  city: "Nasr City",
  governorate: "Cairo",
  country: "EG",
  zone: "METRO",
  carrier: "BOSTA",
  carrierService: "BOSTA EXPRESS METRO",
  initialStatus: "PENDING_CONFIRMATION",
  riskScore: 5,
  riskLevel: "LOW",
  riskReasons: [],
  items: [{sku: "SKU-PROD-001", qty: 1, unitPrice: 150}],
  shippingFee: 0,
  currency: "EGP"
}')"
request 200 "create order" -X POST -H "$auth_header" -H 'Content-Type: application/json' \
  --data "$order_payload" "$base_url/api/internal/orders"
order_id="$(jq -er '.order.id' "$response_file")"
confirmation_token="$(jq -er '.order.confirmationToken' "$response_file")"
customer_id="$(jq -er '.order.customer.id' "$response_file")"

request 200 "get order" -H "$auth_header" "$base_url/api/internal/orders/$order_id"
request 200 "update address" -X POST -H "$auth_header" -H 'Content-Type: application/json' \
  --data '{"addressLine":"15 Updated Test Street","city":"Nasr City","governorate":"Cairo","country":"EG","zone":"METRO","carrier":"BOSTA","carrierService":"BOSTA EXPRESS METRO"}' \
  "$base_url/api/internal/orders/$order_id/address"
request 200 "apply discount" -X POST -H "$auth_header" -H 'Content-Type: application/json' \
  --data '{"percent":10}' "$base_url/api/internal/orders/$order_id/discount"
request 200 "contact attempt" -X POST -H "$auth_header" -H 'Content-Type: application/json' \
  --data '{"actor":"n8n"}' "$base_url/api/internal/orders/$order_id/contact-attempt"
request 200 "stale orders" -H "$auth_header" "$base_url/api/internal/orders/stale"
request 200 "daily report" -H "$auth_header" "$base_url/api/internal/reports/daily?date=$(date +%F)"

request 200 "link Telegram" -X POST -H "$auth_header" -H 'Content-Type: application/json' \
  --data "$(jq -n --arg token "$confirmation_token" --arg chatId "$chat_id" '{token:$token,chatId:$chatId,username:"phase3_test"}')" \
  "$base_url/api/internal/customers/link-telegram"
request 200 "find Telegram customer" -H "$auth_header" "$base_url/api/internal/customers/by-telegram/$chat_id"
request 200 "set pending action" -X POST -H "$auth_header" -H 'Content-Type: application/json' \
  --data "$(jq -n --arg orderId "$order_id" '{action:"AWAIT_ADDRESS",orderId:$orderId}')" \
  "$base_url/api/internal/customers/$customer_id/pending-action"
request 200 "clear pending action" -X POST -H "$auth_header" -H 'Content-Type: application/json' \
  --data '{"action":"NONE"}' "$base_url/api/internal/customers/$customer_id/pending-action"
request 200 "conversation log" -X POST -H "$auth_header" -H 'Content-Type: application/json' \
  --data "$(jq -n --arg orderId "$order_id" --arg customerId "$customer_id" '{orderId:$orderId,customerId:$customerId,channel:"SYSTEM",direction:"IN",messageType:"TEXT",content:"test"}')" \
  "$base_url/api/internal/conversations"
request 200 "order event" -X POST -H "$auth_header" -H 'Content-Type: application/json' \
  --data "$(jq -n --arg orderId "$order_id" '{orderId:$orderId,type:"PHASE3_TEST",actor:"test",message:"API verification event"}')" \
  "$base_url/api/internal/events"

request 200 "confirm transition" -X POST -H "$auth_header" -H 'Content-Type: application/json' \
  --data '{"to":"CONFIRMED","actor":"test"}' "$base_url/api/internal/orders/$order_id/transition"
awb="$(jq -er '.order.awbNumber' "$response_file")"
request 200 "shipping transition" -X POST -H "$auth_header" -H 'Content-Type: application/json' \
  --data "$(jq -n '{status:"IN_TRANSIT",location:"Test hub",occurredAt:(now|todateiso8601)}')" \
  "$base_url/api/internal/shipments/$awb/tracking"

echo "All internal API routes passed. orderId=$order_id awb=$awb"
