import Fuse from "fuse.js";
import state from "../../store";
export default async function listEfiles(db, { data: { tags, limit, orderBy, orderDirection, next, query, jobId }, }) {
  var _a, _b, _c, _d;
  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("efiles", next));
  let efiles = (await db.list("efiles", 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(efiles, {
      keys: ["name"],
    });
    efiles = await fuse.search(query).map((result) => result === null || result === void 0 ? void 0 : result.item);
  }
  if (!efiles)
    return null;
  for (const [index, efile] of Object.entries(efiles)) {
    efiles[index].template = (_d = (_c = state === null || state === void 0 ? void 0 : state.templates) === null || _c === void 0 ? void 0 : _c.find) === null || _d === void 0 ? void 0 : _d.call(_c, (template) => { var _a; return (template === null || template === void 0 ? void 0 : template.id) === ((_a = efile === null || efile === void 0 ? void 0 : efile.template) === null || _a === void 0 ? void 0 : _a.id); });
  }
  return efiles;
}
