import { Request, Response } from "express";
import { SocialNetworkEmailsMethods } from "../../methods/social-network/social-network-email.method";
import { SocialNetworkEmailsModel } from "../../models/social-network/social-network-email.model";
import { AbstractController } from "../abstract.controller";

export class SocialNetworkEmailsController extends AbstractController {
  methods: SocialNetworkEmailsMethods;
  constructor() {
    super(SocialNetworkEmailsModel);
    this.methods = new SocialNetworkEmailsMethods(SocialNetworkEmailsModel);
  }
  /**
   * Create record with public source
   * @param {*} req
   * @param {*} res
   */
  async sendEmail(req: Request, res: Response) {
    try {
      const matchedData = this.params.matchedData(req);
      if (Object.keys(matchedData).length > 0) {
        const senders = [];
        matchedData.list.forEach((item) => {
          const emails = item.email.split(",");
          senders.push(
            ...emails.map((email) => {
              return this.methods.send(
                { subject: item.subject },
                item.html ?? "",
                item.data ?? {},
                email.trim() ?? ""
              );
            })
          );
        });
        Promise.allSettled(senders)
          .then((response) => {
            res.send({ message: "SUCCESS", response });
          })
          .catch((error) => {
            this.params.handleHttpError(res, error);
          });
      } else {
        this.params.handleHttpError(res, "MISSING_DATA");
      }
    } catch (e) {
      this.params.handleHttpError(res, e);
    }
  }
  async sendVerification(req: Request | any, res: Response) {
    try {
      const matchedData = this.params.matchedData(req);
      this.methods
        .sendVerification(matchedData)
        .then((response) => {
          res.send(response);
        })
        .catch((error) => {
          this.params.handleHttpError(res, error);
        });
    } catch (e) {
      console.log(e);
      this.params.handleHttpError(res, e);
    }
  }
  async verify(req: Request | any, res: Response) {
    try {
      const matchedData = this.params.matchedData(req);
      res.send({
        verify: this.methods.verify(matchedData.email, matchedData.code),
      });
    } catch (e) {
      console.log(e);
      this.params.handleHttpError(res, e);
    }
  }
}
