import { formatQuantity, hasQuantity } from "@/lib/fractions";

type ShoppingListMarkdownInput = {
  name: string;
  items: Array<{ rawName: string; quantity: string | null; unit: string | null; aisle: string | null; checked: boolean }>;
};

export function shoppingListToMarkdown(list: ShoppingListMarkdownInput): string {
  const lines: string[] = [`# ${list.name}`, ""];

  const byAisle = new Map<string, typeof list.items>();
  for (const item of list.items) {
    const aisle = item.aisle ?? "Other";
    const group = byAisle.get(aisle) ?? [];
    group.push(item);
    byAisle.set(aisle, group);
  }

  for (const [aisle, items] of byAisle) {
    lines.push(`## ${aisle}`, "");
    for (const item of items) {
      const qty = [hasQuantity(item.quantity) ? formatQuantity(parseFloat(item.quantity!)) : null, item.unit].filter(Boolean).join(" ");
      lines.push(`- [${item.checked ? "x" : " "}] ${qty ? `${qty} ` : ""}${item.rawName}`);
    }
    lines.push("");
  }

  return lines.join("\n").trim() + "\n";
}
