import { UtilsMethods } from "./../methods/util.method";
import { AbstractController } from "./abstract.controller";
import { Request, Response } from "express";
import { EndpointsModel } from "../models/endpoint.model";
import { EndpointsMethods } from "../methods/endpoint.method";

export class EndpointsController extends AbstractController {
  methods: EndpointsMethods;
  utilsMethods: UtilsMethods;
  constructor() {
    super(EndpointsModel);
    this.methods = new EndpointsMethods(EndpointsModel);
    this.utilsMethods = new UtilsMethods(EndpointsModel);
  }
  /**
   * Create record with public source
   * @param {*} req
   * @param {*} res
   */
  async createItem(req: Request, res: Response) {
    try {
      const endpoints = this.utilsMethods.endpointsUtils(req);
      let allEndpoints = endpoints.docs.reduce((prev, next) => {
        return [
          ...prev,
          ...next.methods.map((method) => {
            return {
              path: `${method}${next.path}`,
              store_id: req.headers.store,
            };
          }),
        ];
      }, []);
      allEndpoints = allEndpoints.filter(async (endpoint) => {
        return await !this.model.findOne({
          path: endpoint.path,
        });
      });

      const data = await this.model.bulkWrite(
        allEndpoints.map((endpoint) => ({
          updateOne: {
            filter: { path: endpoint.path },
            update: { $set: endpoint },
            upsert: true,
          },
        }))
      );
      res.send(data);
    } catch (e) {
      this.params.handleHttpError(res, e);
    }
  }
}
