 /**
  * Fill options argument with the defaults
  */
opt = defaults(opt, {
  loadDeleted: false,
  dontLean: false,
});

let { count, page, sort, sort_by } = query;
count = isNaN(count as unknown as number) ? undefined : parseInt(count.toString());
page = isNaN(page as unknown as number) ? 1 : parseInt(page.toString());


let q: mongoose.QueryWithFuzzySearch<EntityAlias> = this.{{SUB_MODULE_ENTITY_CAMELCASED_SINGULAR}}Model.find();
let totalQ: mongoose.QueryWithFuzzySearch<EntityAlias> = this.{{SUB_MODULE_ENTITY_CAMELCASED_SINGULAR}}Model.where();


/**
 * Apply filters
 */
const filter = await this._applyFilters({ q, totalQ, query, authData, opt });
q = filter.q;
totalQ = filter.totalQ;


const limit = (count === undefined || count === null) ? authData?.current?.app?.settings?.listing?.default_count || getRegistry().getConfig('settings.listing.defaultCount') : count;
const { skip, take } = this.getPaginationOptions(limit, page);
const sortOptions = this.getSortOptions(sort, sort_by);
if (take) q = q.limit(take);
if (skip) q = q.skip(skip);
q = q.sort(sortOptions);
q = this.getSelectFields(q, query.fields);
if (!opt.dontLean) q = q.lean() as any;


/**
  * @description Add query to execution scenario
  */
scenario.set({
  request_filter: fixFiltersObject(query.filters),
  listing_query: {
    model: q.model.modelName,
    query: q.getQuery(),
    options: q.getOptions(),
  }
});

/**
  * @description execute the query
  */
const items = await q
  .allowDiskUse(true) // Enable disk usage for large sorting operations
  .exec();


const total = await totalQ.countDocuments();
const pages = limit === -1 ? 1 : Math.ceil(total / limit);

scenario.set({
  skip,
  take,
  found: items?.length,
  total
});

result = {
  data: items.map(doc => mapDocumentToExposed(doc)),
  pagination: {
    total,
    pages,
  }
}
