export type FilterType = {
  id: string;
  label: string;
  count: number;
};

export function groupListByType<T extends Record<string, any>>(
  list: T[] | undefined,
  idField: string,
  labelField: string,
) {
  const fileTypeList: FilterType[] = [];
  const safeList = Array.isArray(list) ? list : [];
  safeList.forEach((x) => {
    const id = x[idField];
    if (id === undefined || id === null) return;
    const label = x[labelField] ?? String(id);
    const item = fileTypeList.find((y) => y.id === id);
    if (!item) {
      fileTypeList.push({ id, label, count: 1 });
    } else {
      item.count += 1;
    }
  });

  return fileTypeList;
}

export function buildOwnersFilter<T extends Record<string, any>>(list: T[]) {
  const owners = groupListByType(list, 'tenant_id', 'nickname');

  return { field: 'owner', list: owners, label: 'Owner' };
}
