class APIFeatures {
  constructor(query, queryString) {
    this.query = query;
    this.queryString = queryString;
    console.log("query", queryString);
  }

  filter(...allowedFields) {
    const newObj = {};
    Object.keys(this.queryString).forEach((el) => {
      if (allowedFields.includes(el)) newObj[el] = this.queryString[el];
    });

    if (newObj.name) newObj.name = { $regex: `${newObj.name}` };
    if (newObj.phone) newObj.phoneNumber = { $regex: `${newObj.phone}` };
    if (newObj.author) newObj.author = { $regex: `${newObj.author}` };
    if (newObj.tags) newObj.tags = { $regex: `${newObj.tags}` };
    this.query = this.query.find(newObj);
    return this;
  }

  sort() {
    if (this.queryString.sort) {
      const sortBy = this.queryString.sort.split(",").join(" ");
      this.query = this.query.sort(sortBy);
    } else {
      this.query = this.query.sort("-publishedAt");
    }

    return this;
  }

  limitFields() {
    if (this.queryString.fields) {
      const fields = this.queryString.fields.split(",").join(" ");
      this.query = this.query.select(fields);
    } else {
      this.query = this.query.select("-__v");
    }

    return this;
  }

  paginate() {
    const page = this.queryString.page * 1 || 1;
    const limit = 9;
    const skip = (page - 1) * limit;
    console.log(`skip:${skip}`);
    this.query = this.query.skip(skip).limit(limit);

    return this;
  }
}
module.exports = APIFeatures;
