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

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

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

/** TC-301：RPA P95 < 30s（需后端 RPA_MOCK_MODE=true） */
export default function rpaP95Test() {
  const customerId = `CUST_LOAD_${__VU}`;
  const headers = {
    "Content-Type": "application/json",
    "x-auth-type": "service",
    "x-customer-id": customerId,
    "x-permissions": "pricing:markup:write",
  };

  const requestId = `00000000-0000-4000-8000-${String(__ITER).padStart(12, "0")}`;
  const body = JSON.stringify({
    request_id: requestId,
    customer_id: customerId,
    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 createRes = http.post(`${BASE_URL}/api/quotes`, body, { headers });
  check(createRes, { "create 200": (r) => r.status === 200 });

  if (createRes.status !== 200) {
    return;
  }

  const quoteId = createRes.json("data.quote_id");
  if (!quoteId) {
    return;
  }

  const deadline = Date.now() + 35_000;
  while (Date.now() < deadline) {
    const pollRes = http.get(`${BASE_URL}/api/quotes/${quoteId}`, { headers });
    if (pollRes.status === 200) {
      const status = pollRes.json("data.status");
      if (status === "done" || status === "failed") {
        check(pollRes, { "poll terminal": () => true });
        return;
      }
    }
    sleep(1);
  }
}
