#!/usr/bin/env bash
# Canlı Railway API — F13 (5 senaryo) + checkout URL retry. Kanıt: frontend/qa/logs/
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
LOG_DIR="$ROOT/frontend/qa/logs"
EVIDENCE="$ROOT/frontend/qa/evidence"
API="${FAUNAMIX_QA_API:-https://faunamix-production.up.railway.app}"
MAX_INIT_ATTEMPTS="${FAUNAMIX_QA_CHECKOUT_ATTEMPTS:-8}"
RETRY_SLEEP="${FAUNAMIX_QA_CHECKOUT_SLEEP:-2}"

mkdir -p "$LOG_DIR" "$EVIDENCE/f13" "$EVIDENCE/c3"

if [[ -f "$ROOT/api/.env.railway" ]]; then
  set -a
  # shellcheck disable=SC1091
  source "$ROOT/api/.env.railway"
  set +a
fi

mysql_q() {
  mysql -h "$DB_HOST" -P "${DB_PORT:-3306}" -u "$DB_USER" -p"$DB_PASS" --protocol=TCP "$DB_NAME" -N -e "$1" 2>/dev/null | grep -v Warning || true
}

checkout_post() {
  local idem="$1"
  local body="$2"
  curl -sS -X POST "$API/api/checkout_create.php" \
    -H "Content-Type: application/json" \
    -H "Idempotency-Key: $idem" \
    -d "$body"
}

checkout_with_url() {
  local idem="$1"
  local body="$2"
  local out attempt raw url
  for ((attempt = 1; attempt <= MAX_INIT_ATTEMPTS; attempt++)); do
    raw="$(checkout_post "$idem" "$body")"
    url="$(echo "$raw" | php -r '$j=json_decode(stream_get_contents(STDIN),true); echo $j["checkout_url"]??"";')"
    if [[ -n "$url" && "$url" != "null" ]]; then
      echo "$raw"
      return 0
    fi
    sleep "$RETRY_SLEEP"
  done
  echo "$raw"
  return 1
}

retry_payment() {
  local token="$1"
  curl -sS -X POST "$API/api/order_retry_payment.php" \
    -H "Content-Type: application/json" \
    -d "{\"token\":\"$token\"}"
}

customer_json() {
  local email="$1"
  local ship="${2:-standard}"
  local coupon="${3:-}"
  php -r "
    echo json_encode([
      'full_name' => 'QA Test',
      'email' => '$email',
      'phone' => '5050000001',
      'identity_no' => '11111111111',
      'city' => 'Muğla',
      'district' => 'Fethiye',
      'address_line' => 'QA adres',
      'postal_code' => '48300',
      'shipping_method' => '$ship',
      'coupon_code' => '$coupon',
    ], JSON_UNESCAPED_UNICODE);
  "
}

legal='{"mesafeli":true,"on_bilgilendirme":true,"iade":true,"gizlilik":true}'

echo "[setup] express surcharge + QA variant"
mysql_q "INSERT INTO ecommerce_kv (k, v) VALUES ('express_shipping_surcharge_try', '49.90')
  ON DUPLICATE KEY UPDATE v = VALUES(v);"

mysql_q "INSERT INTO product_variants (product_id, sku, option_values_json, price_try, stock_quantity, is_active, sort_order)
  SELECT 17, 'QA-VAR-17', '{\"Beden\":\"M\"}', 120.00, 10, 1, 1
  FROM DUAL
  WHERE NOT EXISTS (SELECT 1 FROM product_variants WHERE sku = 'QA-VAR-17' LIMIT 1);"

VARIANT_ID="$(mysql_q "SELECT id FROM product_variants WHERE sku='QA-VAR-17' LIMIT 1;")"
echo "variant_id=$VARIANT_ID" | tee "$EVIDENCE/f13/qa-variant-id.txt"

echo "[C3-prep] product 17 stock_quantity=1"
mysql_q "UPDATE products SET stock_quantity = 1 WHERE id = 17;"
mysql_q "SELECT id, stock_quantity FROM products WHERE id = 17;" | tee "$EVIDENCE/c3/stock-before.txt"

TS="$(date +%s)"

# --- F13 S2: coupon ---
echo "[F13-S2] coupon TESTKUPON"
BODY_S2=$(php -r "
  echo json_encode([
    'items' => [['product_id' => 17, 'quantity' => 1, 'variant_id' => 0]],
    'customer' => json_decode('$(customer_json "qa-f13-s2-$TS@faunamix.test" standard TESTKUPON)', true),
    'legal_acceptances' => json_decode('$legal', true),
  ]);
")
if checkout_with_url "f13-s2-$TS" "$BODY_S2" >"$LOG_DIR/f13-s2-checkout.json"; then
  echo "S2 checkout_url OK"
else
  echo "S2 checkout_url FAIL (see log)"
fi

# --- F13 S3: multi-item ---
echo "[F13-S3] multi-item"
BODY_S3=$(php -r "
  echo json_encode([
    'items' => [
      ['product_id' => 16, 'quantity' => 1, 'variant_id' => 0],
      ['product_id' => 17, 'quantity' => 1, 'variant_id' => 0],
    ],
    'customer' => json_decode('$(customer_json "qa-f13-s3-$TS@faunamix.test")', true),
    'legal_acceptances' => json_decode('$legal', true),
  ]);
")
checkout_with_url "f13-s3-$TS" "$BODY_S3" >"$LOG_DIR/f13-s3-checkout.json" || true

# --- F13 S4: express ---
echo "[F13-S4] express shipping"
BODY_S4=$(php -r "
  echo json_encode([
    'items' => [['product_id' => 17, 'quantity' => 1, 'variant_id' => 0]],
    'customer' => json_decode('$(customer_json "qa-f13-s4-$TS@faunamix.test" express)', true),
    'legal_acceptances' => json_decode('$legal', true),
  ]);
")
checkout_with_url "f13-s4-$TS" "$BODY_S4" >"$LOG_DIR/f13-s4-checkout.json" || true

# --- F13 S5: variant ---
echo "[F13-S5] variant"
BODY_S5=$(php -r "
  echo json_encode([
    'items' => [['product_id' => 17, 'quantity' => 1, 'variant_id' => (int)'$VARIANT_ID']],
    'customer' => json_decode('$(customer_json "qa-f13-s5-$TS@faunamix.test")', true),
    'legal_acceptances' => json_decode('$legal', true),
  ]);
")
checkout_with_url "f13-s5-$TS" "$BODY_S5" >"$LOG_DIR/f13-s5-checkout.json" || true

# --- F13 S6: retry payment ---
echo "[F13-S6] retry payment"
BODY_S6=$(php -r "
  echo json_encode([
    'items' => [['product_id' => 17, 'quantity' => 1, 'variant_id' => 0]],
    'customer' => json_decode('$(customer_json "qa-f13-s6-$TS@faunamix.test")', true),
    'legal_acceptances' => json_decode('$legal', true),
  ]);
")
RAW_S6="$(checkout_post "f13-s6-create-$TS" "$BODY_S6")"
echo "$RAW_S6" >"$LOG_DIR/f13-s6-create.json"
TOKEN_S6="$(echo "$RAW_S6" | php -r '$j=json_decode(stream_get_contents(STDIN),true); echo $j["order_token"]??"";')"
if [[ -n "$TOKEN_S6" ]]; then
  retry_payment "$TOKEN_S6" >"$LOG_DIR/f13-s6-retry.json"
fi

# --- C3: parallel checkout (stock=1) ---
echo "[C3] parallel checkout product 17"
mysql_q "UPDATE products SET stock_quantity = 1 WHERE id = 17;"
BODY_C3=$(php -r "
  echo json_encode([
    'items' => [['product_id' => 17, 'quantity' => 1, 'variant_id' => 0]],
    'customer' => json_decode('$(customer_json "qa-c3-a-$TS@faunamix.test")', true),
    'legal_acceptances' => json_decode('$legal', true),
  ]);
")
BODY_C3B=$(php -r "
  echo json_encode([
    'items' => [['product_id' => 17, 'quantity' => 1, 'variant_id' => 0]],
    'customer' => json_decode('$(customer_json "qa-c3-b-$TS@faunamix.test")', true),
    'legal_acceptances' => json_decode('$legal', true),
  ]);
")

checkout_post "c3-a-$TS" "$BODY_C3" >"$LOG_DIR/c3-checkout-a.json" &
PID_A=$!
checkout_post "c3-b-$TS" "$BODY_C3B" >"$LOG_DIR/c3-checkout-b.json" &
PID_B=$!
wait "$PID_A" "$PID_B"

# Retry URL for C3 if null
for side in a b; do
  f="$LOG_DIR/c3-checkout-$side.json"
  url="$(php -r '$j=json_decode(file_get_contents($argv[1]),true); echo $j["checkout_url"]??"";' "$f")"
  token="$(php -r '$j=json_decode(file_get_contents($argv[1]),true); echo $j["order_token"]??"";' "$f")"
  if [[ -z "$url" || "$url" == "null" ]] && [[ -n "$token" ]]; then
    retry_payment "$token" >"$LOG_DIR/c3-retry-$side.json"
  fi
done

echo "[done] logs in $LOG_DIR"
