import { type Category } from '../types/Category';

export interface FlatCategory {
  id: number;
  name: string;
  level: number;
  parentId: number | null;
  path: string;
  isSelectable: boolean; // True si no tiene hijos
  hasChildren: boolean;
}

interface CategoryNode extends Category {
  children: CategoryNode[];
}

export const buildTree = (categories: Category[]): CategoryNode[] => {
  const map = new Map<number, CategoryNode>();
  const roots: CategoryNode[] = [];

  // 1. Inicializar nodos
  categories.forEach(cat => {
    map.set(cat.id, { ...cat, children: [] });
  });

  // 2. Construir relaciones
  categories.forEach(cat => {
    const node = map.get(cat.id);
    if (node) {
      if (cat.parentId && map.has(cat.parentId)) {
        map.get(cat.parentId)!.children.push(node);
      } else {
        roots.push(node);
      }
    }
  });

  return roots;
};

export const flattenCategoriesForSelect = (
  nodes: CategoryNode[],
  level = 0,
  parentPath = ""
): FlatCategory[] => {
  let result: FlatCategory[] = [];
  const sortedNodes = [...nodes].sort((a, b) => a.name.localeCompare(b.name));

  for (const node of sortedNodes) {
    const currentPath = parentPath ? `${parentPath} > ${node.name}` : node.name;
    const hasChildren = node.children && node.children.length > 0;

    result.push({
      id: node.id,
      name: node.name,
      level: level,
      parentId: node.parentId || null,
      path: currentPath,
      hasChildren: hasChildren,
      isSelectable: !hasChildren
    });

    if (hasChildren) {
      const childrenFlat = flattenCategoriesForSelect(node.children, level + 1, currentPath);
      result = [...result, ...childrenFlat];
    }
  }
  return result;
};

export const processCategories = (rawCategories: Category[]): FlatCategory[] => {
  const tree = buildTree(rawCategories);
  return flattenCategoriesForSelect(tree);
};