import { readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { fetchAssignableStaffMembers } from "../../detail/assignableStaff.js";
function readNonEmptyString(value) {
  if (typeof value !== "string") return null;
  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : null;
}
function extractRelatedEntityOption(item, kind) {
  const id = typeof item.id === "string" ? item.id : null;
  if (!id) return null;
  const displayName = readNonEmptyString(item.displayName) ?? readNonEmptyString(item.display_name);
  const detail = kind === "person" ? readNonEmptyString(item.primaryEmail) ?? readNonEmptyString(item.primary_email) : readNonEmptyString(item.domain) ?? readNonEmptyString(item.websiteUrl) ?? readNonEmptyString(item.website_url);
  const label = displayName ?? detail ?? id;
  return { id, kind, label, subtitle: detail && detail !== label ? detail : null };
}
async function searchRelatedEntities(kind, query, signal) {
  const params = new URLSearchParams({ page: "1", pageSize: "20", sortField: "name", sortDir: "asc" });
  if (query.length) params.set("search", query);
  const endpoint = kind === "person" ? `/api/customers/people?${params.toString()}` : `/api/customers/companies?${params.toString()}`;
  const data = await readApiResultOrThrow(endpoint, { signal });
  const items = Array.isArray(data?.items) ? data.items : [];
  return items.map((item) => item && typeof item === "object" ? extractRelatedEntityOption(item, kind) : null).filter((option) => option !== null);
}
async function fetchRelatedEntityOfKind(kind, entityId, signal) {
  const params = new URLSearchParams({ page: "1", pageSize: "1", ids: entityId });
  const endpoint = kind === "person" ? `/api/customers/people?${params.toString()}` : `/api/customers/companies?${params.toString()}`;
  try {
    const data = await readApiResultOrThrow(endpoint, { signal });
    const item = Array.isArray(data?.items) ? data.items[0] : null;
    return item && typeof item === "object" ? extractRelatedEntityOption(item, kind) : null;
  } catch {
    return null;
  }
}
async function fetchRelatedEntityById(entityId, signal) {
  const [person, company] = await Promise.all([
    fetchRelatedEntityOfKind("person", entityId, signal),
    fetchRelatedEntityOfKind("company", entityId, signal)
  ]);
  return person ?? company;
}
function extractDealOption(item) {
  const id = typeof item.id === "string" ? item.id : null;
  if (!id) return null;
  const label = readNonEmptyString(item.title) ?? id;
  return { id, label };
}
async function fetchDealsForEntity(entity, signal) {
  const params = new URLSearchParams({ page: "1", pageSize: "20" });
  params.set(entity.kind === "person" ? "personId" : "companyId", entity.id);
  const data = await readApiResultOrThrow(
    `/api/customers/deals?${params.toString()}`,
    { signal }
  );
  const items = Array.isArray(data?.items) ? data.items : [];
  return items.map((item) => item && typeof item === "object" ? extractDealOption(item) : null).filter((option) => option !== null);
}
async function fetchDealById(dealId, signal) {
  try {
    const params = new URLSearchParams({ page: "1", pageSize: "1", ids: dealId });
    const data = await readApiResultOrThrow(
      `/api/customers/deals?${params.toString()}`,
      { signal }
    );
    const item = Array.isArray(data?.items) ? data.items[0] : null;
    return item && typeof item === "object" ? extractDealOption(item) : null;
  } catch {
    return null;
  }
}
async function searchPeopleOptions(query, options) {
  const [staff, customers] = await Promise.all([
    options.includeStaff === false ? Promise.resolve([]) : fetchAssignableStaffMembers(query, { pageSize: 10, signal: options.signal }).catch(() => []),
    options.includeCustomers ? searchRelatedEntities("person", query, options.signal) : Promise.resolve([])
  ]);
  const staffOptions = staff.map((member) => ({
    userId: member.userId,
    name: member.displayName,
    email: member.email,
    isCustomer: false
  }));
  const customerOptions = customers.map((person) => ({
    userId: person.id,
    name: person.label,
    email: person.subtitle,
    isCustomer: true
  }));
  return [...staffOptions, ...customerOptions];
}
const RESOURCE_PAGE_SIZE = 20;
async function searchResourceOptions(params, signal) {
  const search = new URLSearchParams({
    page: "1",
    pageSize: String(RESOURCE_PAGE_SIZE),
    sortField: "name",
    sortDir: "asc",
    isActive: "true"
  });
  if (params.query.length) search.set("search", params.query);
  if (params.resourceTypeId) search.set("resourceTypeId", params.resourceTypeId);
  const data = await readApiResultOrThrow(
    `/api/resources/resources?${search.toString()}`,
    { signal }
  );
  const rows = Array.isArray(data?.items) ? data.items : [];
  const items = rows.map((item) => {
    if (!item || typeof item !== "object") return null;
    const id = typeof item.id === "string" ? item.id : null;
    if (!id) return null;
    const label = readNonEmptyString(item.name) ?? id;
    return { id, label };
  }).filter((option) => option !== null);
  const total = typeof data?.total === "number" && Number.isFinite(data.total) ? data.total : items.length;
  return { items, total };
}
async function fetchResourceTypes(signal) {
  const params = new URLSearchParams({
    page: "1",
    pageSize: "100",
    sortField: "name",
    sortDir: "asc",
    withResourceCounts: "true"
  });
  try {
    const data = await readApiResultOrThrow(
      `/api/resources/resource-types?${params.toString()}`,
      { signal }
    );
    const rows = Array.isArray(data?.items) ? data.items : [];
    return rows.map((item) => {
      if (!item || typeof item !== "object") return null;
      const id = typeof item.id === "string" ? item.id : null;
      if (!id) return null;
      const name = readNonEmptyString(item.name) ?? id;
      const rawCount = item.resourceCount;
      const count = typeof rawCount === "number" && Number.isFinite(rawCount) ? rawCount : 0;
      return { id, name, count };
    }).filter((type) => type !== null);
  } catch {
    return [];
  }
}
async function fetchPeoplePhones(ids, signal) {
  const unique = Array.from(new Set(ids.filter((id) => typeof id === "string" && id.length > 0)));
  if (unique.length === 0) return [];
  const params = new URLSearchParams({ page: "1", pageSize: "100", ids: unique.join(",") });
  try {
    const data = await readApiResultOrThrow(
      `/api/customers/people?${params.toString()}`,
      { signal }
    );
    const items = Array.isArray(data?.items) ? data.items : [];
    const result = [];
    for (const item of items) {
      if (!item || typeof item !== "object") continue;
      const id = typeof item.id === "string" ? item.id : null;
      const phone = readNonEmptyString(item.primaryPhone) ?? readNonEmptyString(item.primary_phone);
      if (!id || !phone) continue;
      const name = readNonEmptyString(item.displayName) ?? readNonEmptyString(item.display_name) ?? id;
      result.push({ id, name, phone });
    }
    return result;
  } catch {
    return [];
  }
}
async function findStaffMemberName(userId, signal) {
  try {
    const members = await fetchAssignableStaffMembers("", { pageSize: 100, signal });
    const match = members.find((member) => member.userId === userId);
    return match ? match.displayName : null;
  } catch {
    return null;
  }
}
export {
  fetchDealById,
  fetchDealsForEntity,
  fetchPeoplePhones,
  fetchRelatedEntityById,
  fetchResourceTypes,
  findStaffMemberName,
  searchPeopleOptions,
  searchRelatedEntities,
  searchResourceOptions
};
//# sourceMappingURL=lookups.js.map
