import type { Department, Member } from './members';

interface FilterMembersForListInput {
  members: Member[];
  departments: Department[];
  activeDeptId: string | null;
  nameKeyword: string;
}

function collectDepartmentTreeIds(departments: Department[], departmentId: string): Set<string> {
  const ids = new Set<string>([departmentId]);
  let changed = true;

  while (changed) {
    changed = false;
    for (const department of departments) {
      if (department.parentId && ids.has(department.parentId) && !ids.has(department.id)) {
        ids.add(department.id);
        changed = true;
      }
    }
  }

  return ids;
}

export function filterMembersForList({
  members,
  departments,
  activeDeptId,
  nameKeyword,
}: FilterMembersForListInput): Member[] {
  const keyword = nameKeyword.trim().toLowerCase();
  const visibleDepartmentIds = activeDeptId ? collectDepartmentTreeIds(departments, activeDeptId) : null;

  return members.filter((member) => {
    if (visibleDepartmentIds && !visibleDepartmentIds.has(member.departmentId)) return false;
    if (!keyword) return true;
    return member.name.toLowerCase().includes(keyword);
  });
}

export function resolveLatestEditingMember(editingMember: Member | null, members: Member[]): Member | null {
  if (!editingMember) return null;
  return members.find((member) => member.id === editingMember.id) ?? editingMember;
}

export function getDisplayedAccountPassword(member: Member | null, generatedPassword: string): string {
  return member?.password || generatedPassword;
}
