import http from "k6/http";
import { check } from "k6";

const BASE_URL = __ENV.BASE_URL || "http://localhost:3000";
const CUSTOMER_ID = __ENV.CUSTOMER_ID || "CUST_001";

export const options = {
  vus: 20,
  iterations: 100,
  thresholds: {
    http_req_duration: ["p(95)<300"],
  },
};

const headers = {
  "Content-Type": "application/json",
  "x-auth-type": "service",
  "x-customer-id": CUSTOMER_ID,
  "x-permissions": "pricing:markup:write",
};

/** TC-302：L2 命中 P95 < 300ms（需预热缓存） */
export default function l2P95Test() {
  const body = JSON.stringify({
    request_id: `00000000-0000-4000-8000-${String(__ITER).padStart(12, "0")}`,
    customer_id: CUSTOMER_ID,
    pickup_address: {
      street: "1234 Warehouse Blvd",
      city: "Los Angeles",
      state: "CA",
      zip: "90001",
      place_id: "ChIJ_pickup",
      formatted_address: "1234 Warehouse Blvd, Los Angeles, CA 90001, USA",
      selected_from_suggestions: true,
    },
    delivery_address: {
      street: "5678 Distribution Dr",
      city: "Dallas",
      state: "TX",
      zip: "75201",
      place_id: "ChIJ_delivery",
      formatted_address: "5678 Distribution Dr, Dallas, TX 75201, USA",
      selected_from_suggestions: true,
    },
    weight: { value: 500, unit: "lb" },
    dimensions: { length: 48, width: 40, height: 48, unit: "in" },
    pallet_count: 2,
    cargo_type: "general_freight",
  });

  const res = http.post(`${BASE_URL}/api/quotes`, body, { headers });
  check(res, {
    "status 200": (r) => r.status === 200,
    "cache hit": (r) => {
      try {
        return r.json("data.source_type") === "cache";
      } catch {
        return false;
      }
    },
  });
}
