import Fuse from "fuse.js";
import state from "../../store";
export default async function listScopeServices(db, { data: { tags, limit, orderBy, orderDirection, next, query, jobId, siteId }, }) {
  var _a, _b;
  const collectionPath = `${jobId ? `jobs/${jobId}/` : siteId ? `sites/${siteId}/` : ""}services`;
  const where = [];
  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(collectionPath, next));
  let services = (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,
  })).map((scopeService) => {
    var _a, _b;
    return {
      ...scopeService,
      service: (_b = (_a = state === null || state === void 0 ? void 0 : state.services) === null || _a === void 0 ? void 0 : _a.find) === null || _b === void 0 ? void 0 : _b.call(_a, (service) => { var _a; return (service === null || service === void 0 ? void 0 : service.id) === ((_a = scopeService === null || scopeService === void 0 ? void 0 : scopeService.service) === null || _a === void 0 ? void 0 : _a.id); }),
    };
  });
  if (query === null || query === void 0 ? void 0 : query.length) {
    const fuse = new Fuse(services, {
      keys: ["name"],
    });
    services = await fuse.search(query).map((result) => result === null || result === void 0 ? void 0 : result.item);
  }
  if (!services)
    return null;
  return services;
}
//# sourceMappingURL=listScopeServices.js.map