import { expect } from "@playwright/test";
import { apiRequest } from "./api.js";
function readId(payload, keys) {
  if (!payload || typeof payload !== "object") return null;
  const map = payload;
  for (const key of keys) {
    const value = map[key];
    if (typeof value === "string" && value.length > 0) return value;
  }
  for (const value of Object.values(map)) {
    if (value && typeof value === "object" && !Array.isArray(value)) {
      const nested = readId(value, keys);
      if (nested) return nested;
    }
  }
  return null;
}
async function createEntity(request, token, path, data, idKeys) {
  const response = await apiRequest(request, "POST", path, { token, data });
  const body = await response.json();
  expect(response.ok(), `Failed POST ${path}: ${response.status()}`).toBeTruthy();
  const id = readId(body, idKeys);
  expect(id, `No id in POST ${path} response`).toBeTruthy();
  return id;
}
async function createSalesQuoteFixture(request, token, currencyCode = "USD") {
  return createEntity(request, token, "/api/sales/quotes", { currencyCode }, ["id", "quoteId"]);
}
async function createSalesOrderFixture(request, token, currencyCode = "USD") {
  return createEntity(request, token, "/api/sales/orders", { currencyCode }, ["id", "orderId"]);
}
async function createOrderLineFixture(request, token, orderId, data) {
  return createEntity(
    request,
    token,
    "/api/sales/order-lines",
    {
      orderId,
      currencyCode: "USD",
      quantity: 1,
      name: `QA line ${Date.now()}`,
      unitPriceNet: 10,
      unitPriceGross: 12,
      ...data ?? {}
    },
    ["id", "lineId"]
  );
}
async function createShipmentFixture(request, token, orderId, items) {
  return createEntity(
    request,
    token,
    "/api/sales/shipments",
    { orderId, items },
    ["id", "shipmentId"]
  );
}
async function canManageSalesOrders(request, token) {
  const response = await apiRequest(request, "POST", "/api/sales/orders", {
    token,
    data: { currencyCode: "USD" }
  });
  if (response.status() === 403) return false;
  if (!response.ok()) return false;
  const id = readId(await response.json(), ["id", "orderId"]);
  if (id) {
    try {
      await apiRequest(request, "DELETE", "/api/sales/orders", { token, data: { id } });
    } catch {
    }
  }
  return true;
}
async function deleteSalesEntityIfExists(request, token, path, id) {
  if (!token || !id) return;
  try {
    await apiRequest(request, "DELETE", `${path}?id=${encodeURIComponent(id)}`, { token });
  } catch {
    return;
  }
}
export {
  canManageSalesOrders,
  createOrderLineFixture,
  createSalesOrderFixture,
  createSalesQuoteFixture,
  createShipmentFixture,
  deleteSalesEntityIfExists
};
//# sourceMappingURL=salesFixtures.js.map
