import { Request, Response } from "express";
import mongoose, { Model } from "mongoose";

export class AbstractMethods {
  model: Model<any> | any;

  constructor(model) {
    this.model = model;
  }
  mainFilter(request: Request | any) {
    const store: any = request.headers.store;
    let storeMatch = [];
    if (mongoose.Types.ObjectId.isValid(store)) {
      storeMatch = [
        {
          $match: {
            store_id: new mongoose.Types.ObjectId(store),
            user_id: new mongoose.Types.ObjectId(request.user_id),
          },
        },
      ];
    } else {
      storeMatch = [
        {
          $match: {
            store_id: store,
            user_id: new mongoose.Types.ObjectId(request.user_id),
          },
        },
      ];
    }
    return [
      ...storeMatch,
      {
        $match: {
          deleted: false,
          user_id: new mongoose.Types.ObjectId(request.user_id),
        },
      },
    ];
  }
  async existDocument(filter) {
    return await this.model.findOne(filter).select("_id").lean();
  }
  async existDocuments(filter) {
    const promises = filter.map((f) => {
      return this.model.findOne(f).select("_id").lean();
    });

    return await Promise.allSettled(promises);
  }
  async saveDocument(data, req) {
    if (!req.headers.store) {
      return Error("STORE_NOT_FOUND");
    }
    if (!req.user_id) {
      return Error("USER_NOT_FOUND");
    }
    return await this.model.create({ ...data, store_id: req.headers.store, user_id: req.user_id });
  }
  async saveDocuments() { }
}
