import Fuse from "fuse.js";
import pick from "../../helpers/pick";
import listScopeServices from "../service/listScopeServices";
export default async function listSites(db, { data: { tags, limit, orderBy, orderDirection, next, query, jobId }, }, filterKeys = [
  "id",
  "name",
  "level",
  "class",
  "chamber",
  "floorType",
  "wallType",
  "ceilingType",
  "areas",
  "dots",
  "areaTotalSqft",
  "areaTotalCuft",
  "affectedAreas",
  "affectedAreaTotalSqft",
  "affectedAreaTotalCuft",
  "photos",
  "inventories",
  "services",
  "offsets",
]) {
  var _a, _b;
  const where = [];
  if (jobId)
    where.push({
      key: "job",
      conditional: "==",
      value: db.document("jobs", jobId),
    });
  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("sites", next));
  let sites = (await db.list("sites", where, `${orderBy || "createdAt"}:${orderDirection || "desc"}`, limit, startAfter && {
    startAfter: (_b = (_a = startAfter === null || startAfter === void 0 ? void 0 : startAfter.data) === null || _a === void 0 ? void 0 : _a.call(startAfter)) === null || _b === void 0 ? void 0 : _b.createdAt,
  }));
  for (const [index, site] of Object.entries(sites)) {
    site.services = await listScopeServices(db, {
      data: { siteId: site === null || site === void 0 ? void 0 : site.id },
    });
    sites[index] = filterKeys ? pick(site, filterKeys) : site;
  }
  if (query === null || query === void 0 ? void 0 : query.length) {
    const fuse = new Fuse(sites, {
      keys: ["name"],
    });
    sites = await fuse.search(query).map((result) => result === null || result === void 0 ? void 0 : result.item);
  }
  if (!sites)
    return null;
  return sites.sort((a, b) => (a.name > b.name ? 1 : -1));
}
