import type { DolibarrCategory } from '../services/category.service';

export interface Category {
  id:       number;
  label:    string;
  parentId: number | null;
  children: Category[];
  productCount: number;
}

// Transforme la liste plate Dolibarr en arbre catégorie/sous-catégories
export const buildCategoryTree = (flat: DolibarrCategory[], productCounts: Map<number, number>): Category[] => {
  const map = new Map<number, Category>();

  flat.forEach((c) => {
    const id = Number(c.id);
    const parentId = Number(c.fk_parent) > 0 ? Number(c.fk_parent) : null;

    map.set(id, {
      id,
      label: c.label,
      parentId,
      children: [],
      productCount: productCounts.get(id) ?? 0,
    });
  });

  const roots: Category[] = [];

  map.forEach((cat) => {
    if (cat.parentId !== null && map.has(cat.parentId)) {
      map.get(cat.parentId)!.children.push(cat);
    } else {
      roots.push(cat);
    }
  });

  // Cumule récursivement le productCount des enfants dans chaque parent
  const sumChildren = (cat: Category): number => {
    const childrenSum = cat.children.reduce((acc, child) => acc + sumChildren(child), 0);
    cat.productCount += childrenSum;
    return cat.productCount;
  };

  roots.forEach(sumChildren);

  return roots;
};

export const getAllDescendantIds = (cat: Category): number[] => {
  return [cat.id, ...cat.children.flatMap(getAllDescendantIds)];
};

export const findCategoryById = (tree: Category[], id: number): Category | undefined => {
  for (const cat of tree) {
    if (cat.id === id) return cat;
    const found = findCategoryById(cat.children, id);
    if (found) return found;
  }
  return undefined;
};