import type { InternetPlanCatalogItem } from "@customer-portal/domain/services";

export type InternetOfferingTypeGroup = {
  offeringType: string;
  plans: InternetPlanCatalogItem[];
};

/**
 * Group plans by `internetOfferingType`, preserving input order.
 * If the offering type is missing, plans are grouped under "Other".
 */
export function groupPlansByOfferingType(
  plans: InternetPlanCatalogItem[]
): InternetOfferingTypeGroup[] {
  const groups: InternetOfferingTypeGroup[] = [];
  const indexByKey = new Map<string, number>();

  for (const plan of plans) {
    const offeringType = String(plan.internetOfferingType || "").trim() || "Other";
    const key = offeringType.toLowerCase();
    const idx = indexByKey.get(key);
    if (typeof idx === "number") {
      groups[idx]?.plans.push(plan);
      continue;
    }
    indexByKey.set(key, groups.length);
    groups.push({ offeringType, plans: [plan] });
  }

  return groups;
}
