/** Shape returned on customer list/detail for broker (individual) property rows */
export type BrokerPropertyFields = {
  title?: string | null;
  projectName?: string | null;
  configurationName?: string | null;
  bedrooms?: number | null;
  localityName?: string | null;
  cityName?: string | null;
  stateName?: string | null;
};

function configurationSegment(p: BrokerPropertyFields): string | null {
  const cfg = p.configurationName?.trim();
  if (cfg) return cfg;
  if (p.bedrooms != null && p.bedrooms > 0) return `${p.bedrooms} bhk`;
  return null;
}

export function formatBrokerPropertyLine(
  p: BrokerPropertyFields | null | undefined,
  fallbackTitle?: string | null,
): string {
  const parts = [
    p?.projectName?.trim() || null,
    configurationSegment(p || {}),
    p?.localityName?.trim() || null,
    p?.cityName?.trim() || null,
    p?.stateName?.trim() || null,
  ].filter(Boolean) as string[];

  if (parts.length > 0) return parts.join(", ");

  const title = p?.title?.trim() || fallbackTitle?.trim() || "";
  if (title) return title;
  return "--";
}

export function getBrokerPropertyFromCustomer(customer: {
  unitBookingOrHold?: { property?: BrokerPropertyFields };
  sales?: Array<{ kind?: string; property?: BrokerPropertyFields }>;
  propertyTitle?: string | null;
}): BrokerPropertyFields | undefined {
  const uboh = customer?.unitBookingOrHold?.property;
  if (uboh && typeof uboh === "object") return uboh;

  const propertySale = customer?.sales?.find(
    (s) =>
      s?.property &&
      typeof s.property === "object" &&
      (s.property.title || s.property.projectName),
  );
  if (propertySale?.property) return propertySale.property;

  const anyWithTitle = customer?.sales?.find((s) => s?.property?.title);
  if (anyWithTitle?.property) return anyWithTitle.property;

  if (customer?.propertyTitle)
    return { title: customer.propertyTitle };
  return undefined;
}

export function formatBrokerCustomerProperty(customer: {
  unitBookingOrHold?: { property?: BrokerPropertyFields };
  sales?: Array<{ kind?: string; property?: BrokerPropertyFields }>;
  propertyTitle?: string | null;
}): string {
  const p = getBrokerPropertyFromCustomer(customer);
  return formatBrokerPropertyLine(p, customer?.propertyTitle);
}

export function formatBrokerConfigurationLabel(
  p: BrokerPropertyFields | null | undefined,
): string {
  if (!p) return "-";
  const cfg = p.configurationName?.trim();
  if (cfg) return cfg;
  if (p.bedrooms != null && p.bedrooms > 0) return `${p.bedrooms} BHK`;
  return "-";
}

export function formatBrokerLocalityLabel(
  p: BrokerPropertyFields | null | undefined,
): string {
  if (!p) return "-";
  const parts = [p.localityName, p.cityName, p.stateName]
    .map((x) => (typeof x === "string" ? x.trim() : ""))
    .filter(Boolean);
  return parts.length > 0 ? parts.join(", ") : "-";
}
