import Fuse from "fuse.js";
import state from "../../store";
export default async function listUsers(db, { data: { tags, limit, next, query, ids, locationId, role, roles }, }) {
  var _a;
  const where = [];
  if (ids === null || ids === void 0 ? void 0 : ids.length)
    where.push({
      key: "id",
      conditional: "in",
      value: ids,
    });
  if (roles === null || roles === void 0 ? void 0 : roles.length)
    where.push({ key: "role", conditional: "in", value: roles });
  if (role)
    where.push({
      key: "role",
      conditional: "==",
      value: role,
    });
  if (locationId)
    where.push({
      key: "location",
      conditional: "==",
      value: db.document("locations", locationId),
    });
  if (tags === null || tags === void 0 ? void 0 : tags.length)
    where.push({
      key: "tags",
      conditional: "array-contains-any",
      value: tags,
    });
  const startAfter = (next === null || next === void 0 ? void 0 : next.length) && (await db.getDocument("users", next));
  const { firstName, lastName } = ((_a = startAfter === null || startAfter === void 0 ? void 0 : startAfter.data) === null || _a === void 0 ? void 0 : _a.call(startAfter)) || {};
  let users = (await db.list("users", where, "firstName:asc,lastName:asc", query ? null : limit, startAfter && {
    startAfter: [firstName, lastName],
  }));
  for (const user of Object.values(users)) {
    state.users[user === null || user === void 0 ? void 0 : user.id] = user;
  }
  state.users = { ...state.users };
  if (query === null || query === void 0 ? void 0 : query.length) {
    const fuse = new Fuse(users, {
      keys: ["firstName", "lastName", "address.full", "email", "phone"],
    });
    users = await fuse.search(query, { limit }).map((result) => result === null || result === void 0 ? void 0 : result.item);
  }
  if (!users)
    return null;
  return users;
}
