export type TeamViewMode = 'self' | 'team';

export interface TeamSelectableUser {
  userId: string;
  userNickname: string;
}

export interface TeamSelectionState {
  mode: TeamViewMode;
  selectedUserId: string | null;
  selectedUserIds: string[] | null;
  isRootSelected: boolean;
}

export interface TeamViewContext extends TeamSelectionState {
  allSubordinateUserIds: string[];
  selectedLabel: string;
}

export function resolveTeamQueryUserIds(context: TeamViewContext | null | undefined): string[] | null {
  if (!context || context.mode !== 'team') {
    return null;
  }

  if (context.isRootSelected) {
    return [...context.allSubordinateUserIds];
  }

  return context.selectedUserIds ? [...context.selectedUserIds] : [];
}

export function collectSubordinateUserIds(root: Api.SystemManage.MySubordinateTreeNode | null | undefined): string[] {
  if (!root) return [];

  const ids: string[] = [];

  const walk = (nodes?: Api.SystemManage.MySubordinateTreeNode[] | null) => {
    nodes?.forEach(node => {
      ids.push(node.userId);
      walk(node.children ?? null);
    });
  };

  walk(root.children ?? null);
  return ids;
}

export function findSubordinateNode(
  root: Api.SystemManage.MySubordinateTreeNode | null | undefined,
  userId: string | null
): Api.SystemManage.MySubordinateTreeNode | null {
  if (!root || !userId) return null;

  if (root.userId === userId) {
    return root;
  }

  const stack = [...(root.children ?? [])];
  while (stack.length) {
    const current = stack.shift()!;
    if (current.userId === userId) {
      return current;
    }
    if (current.children?.length) {
      stack.push(...current.children);
    }
  }

  return null;
}
