import Fuse from "fuse.js";
import isAdmin from "../../helpers/auth/isAdmin";
export default async function listFeeds(db, { type, jobId, userId, next, limit, orderBy, orderDirection, query, myFeed, locationId, locationsFeed, }) {
  var _a, _b;
  const collectionPath = "feeds";
  const where = [];
  if (locationsFeed === null || locationsFeed === void 0 ? void 0 : locationsFeed.length)
    where.push({
      key: "location",
      conditional: "in",
      value: locationsFeed.map((id) => db.document("locations", id)),
    });
  if (jobId)
    where.push({
      key: "job",
      conditional: "==",
      value: db.document("jobs", jobId),
    });
  if (locationId)
    where.push({
      key: "location",
      conditional: "==",
      value: db.document("locations", locationId),
    });
  if (userId)
    where.push({
      key: "user",
      conditional: "==",
      value: db.document("users", userId),
    });
  if (type === null || type === void 0 ? void 0 : type.length)
    where.push({
      key: "type",
      conditional: "in",
      value: type,
    });
  if ((myFeed && !isAdmin()) || (isAdmin() && !(jobId || userId) && myFeed))
    where.push({
      key: "userIds",
      conditional: "array-contains",
      value: myFeed,
    });
  const startAfter = (next === null || next === void 0 ? void 0 : next.length) && (await db.getDocument(collectionPath, next));
  console.log("Listing Feed Where: ", where);
  let feeds = (await db.list(collectionPath, 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,
  }));
  if (query === null || query === void 0 ? void 0 : query.length) {
    const fuse = new Fuse(feeds, {
      keys: ["html"],
    });
    feeds = await fuse.search(query).map((result) => result === null || result === void 0 ? void 0 : result.item);
  }
  if (!feeds)
    return null;
  return feeds;
}
