/**
 * 부서관리 타입 정의
 * @description 무제한 깊이 트리 구조 지원
 */

/**
 * 부서 데이터 (무제한 깊이 재귀 구조)
 */
export interface Department {
  id: number;
  name: string;
  parentId: number | null;
  depth: number;           // 깊이 (0: 최상위, 1, 2, 3, ... 무제한)
  children?: Department[]; // 하위 부서 (재귀 - 무제한 깊이)
}

/**
 * 부서 추가/수정 다이얼로그 Props
 */
export interface DepartmentDialogProps {
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
  mode: 'add' | 'edit';
  parentDepartment?: Department;  // 추가 시 부모 부서
  department?: Department;        // 수정 시 대상 부서
  onSubmit: (name: string) => void;
}

/**
 * 트리 아이템 Props (재귀 렌더링)
 */
export interface DepartmentTreeItemProps {
  department: Department;
  depth: number;
  expandedIds: Set<number>;
  selectedIds: Set<number>;
  onToggleExpand: (id: number) => void;
  onToggleSelect: (id: number) => void;
  onAdd: (parentId: number) => void;
  onEdit: (department: Department) => void;
  onDelete: (department: Department) => void;
}

/**
 * 부서 통계 Props
 */
export interface DepartmentStatsProps {
  totalCount: number;
}

/**
 * 툴바 Props
 */
export interface DepartmentToolbarProps {
  totalCount: number;
  selectedCount: number;
  searchQuery: string;
  onSearchChange: (query: string) => void;
  onAdd: () => void;
  onDelete: () => void;
}

/**
 * 트리 컨테이너 Props
 */
export interface DepartmentTreeProps {
  departments: Department[];
  expandedIds: Set<number>;
  selectedIds: Set<number>;
  onToggleExpand: (id: number) => void;
  onToggleSelect: (id: number) => void;
  onToggleSelectAll: () => void;
  onAdd: (parentId: number) => void;
  onEdit: (department: Department) => void;
  onDelete: (department: Department) => void;
}

/**
 * 전체 부서 수 계산 유틸리티 (재귀)
 */
export const countAllDepartments = (departments: Department[]): number => {
  return departments.reduce((count, dept) => {
    return count + 1 + (dept.children ? countAllDepartments(dept.children) : 0);
  }, 0);
};

/**
 * 모든 부서 ID 추출 유틸리티 (재귀 - 전체 선택용)
 */
export const getAllDepartmentIds = (departments: Department[]): number[] => {
  return departments.flatMap(dept => [
    dept.id,
    ...(dept.children ? getAllDepartmentIds(dept.children) : [])
  ]);
};

/**
 * ID로 부서 찾기 (재귀)
 */
export const findDepartmentById = (departments: Department[], id: number): Department | null => {
  for (const dept of departments) {
    if (dept.id === id) return dept;
    if (dept.children) {
      const found = findDepartmentById(dept.children, id);
      if (found) return found;
    }
  }
  return null;
};
