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

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

/**
 * 부서 폼 데이터
 */
export interface DepartmentFormData {
  code: string;
  name: string;
  description: string;
  sortOrder: number;
  isActive: boolean;
}

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

/**
 * 상태 필터 타입
 */
export type StatusFilter = 'all' | 'active' | 'inactive';

/**
 * 툴바 Props
 */
export interface DepartmentToolbarProps {
  totalCount: number;
  selectedCount: number;
  searchQuery: string;
  onSearchChange: (query: string) => void;
  statusFilter: StatusFilter;
  onStatusFilterChange: (filter: StatusFilter) => 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;
};

/**
 * 트리 필터링 유틸리티 (재귀 — 검색/상태 필터)
 * 자식이 매칭되면 부모도 유지
 */
export const filterDepartmentTree = (
  departments: Department[],
  searchQuery: string,
  statusFilter: StatusFilter,
): Department[] => {
  const query = searchQuery.trim().toLowerCase();

  const filterNode = (dept: Department): Department | null => {
    // 자식 먼저 필터링
    const filteredChildren = dept.children
      ? dept.children.map(filterNode).filter(Boolean) as Department[]
      : [];

    // 현재 노드가 매칭되는지 확인
    const matchesSearch = !query ||
      dept.name.toLowerCase().includes(query) ||
      (dept.code && dept.code.toLowerCase().includes(query));

    const matchesStatus = statusFilter === 'all' ||
      (statusFilter === 'active' && dept.isActive) ||
      (statusFilter === 'inactive' && !dept.isActive);

    // 자식이 매칭되면 부모도 유지
    if (filteredChildren.length > 0) {
      return { ...dept, children: filteredChildren };
    }

    // 현재 노드가 매칭되면 유지
    if (matchesSearch && matchesStatus) {
      return { ...dept, children: [] };
    }

    return null;
  };

  return departments.map(filterNode).filter(Boolean) as Department[];
};
