import { CategoryStatus, MAX_CATEGORIES_CHILDREN } from './constants';
import {
  type Category,
  type CategoryAutocompleteOption,
  type CategoryStatusType,
} from './types';

export const getCategoryStatusType = (status: CategoryStatusType) => {
  switch (status) {
    case CategoryStatus.ACTIVE:
      return 'success' as const;
    case CategoryStatus.INACTIVE:
      return 'neutral' as const;
  }
};

/**
 * Flattens a nested category tree into a flat list of options for autocomplete.
 * Each option's label shows the full path (e.g., "Parent > Child > Grandchild").
 */
export const flattenCategoriesToOptions = (
  categories: Category[],
  parentPath = '',
  currentDepth = 1,
): CategoryAutocompleteOption[] => {
  const shouldStopRecursion = currentDepth >= MAX_CATEGORIES_CHILDREN;

  return categories.flatMap(category => {
    const { id, name, children = [] } = category;

    const fullPath = parentPath ? `${parentPath} > ${name}` : name;

    const currentOption: CategoryAutocompleteOption = {
      value: id,
      label: fullPath,
      childrenCount: children.length,
      depth: currentDepth,
    };

    if (shouldStopRecursion) return [currentOption];

    const childOptions = flattenCategoriesToOptions(
      children,
      fullPath,
      currentDepth + 1,
    );

    return [currentOption, ...childOptions];
  });
};

export const formatCategoryLabel = (
  category?: Category,
  showChildren: boolean = false,
) => {
  if (!category) return '-';
  if (!showChildren) return category.name;

  const grandchildren =
    category.children?.map(grandchild => grandchild.name).join(' / ') || '';

  return [category.name, grandchildren].filter(string => !!string).join(' > ');
};

export const hasChildren = (category: { children?: any[] }) =>
  !!category.children && category.children.length > 0;

export const hasMaxChildren = (category: { children?: any[] }) =>
  !!category.children && category.children.length >= MAX_CATEGORIES_CHILDREN;
