import mongoose from "mongoose";
import { AbstractMethods } from "../abstract.method";
import { Vonage } from "@vonage/server-sdk";

const verifications = [];
export class SocialNetworkSmssMethods extends AbstractMethods {
  api: any = {
    apiKey: process.env.VONAGE_APIKEY,
    apiSecret: process.env.VONAGE_APISECRET,
  };
  vonage = new Vonage(this.api);
  constructor(model) {
    super(model);
  }
  async sendVerification(body: { number: string }) {
    try {
      const code = Math.floor(Math.random() * (9999 - 1000 + 1) + 1000) + "";

      verifications[body.number] = code;
      const from = "Cupen Sys";
      const text = `Code: ${code}.`;
      return await this.sendMessages(
        [{ number: body.number, message: text }],
        from
      );
    } catch (error) {
      console.log(error);
      throw error;
    }
  }
  verify(number, code) {
    return verifications[number] + "" === code + "";
  }
  async sendMessages(
    list: { number: string; message: string }[],
    from = "No reply"
  ) {
    return new Promise((resolve, reject) => {
      try {
        const listPromises = list.map((item) => {
          return this.vonage.sms.send({
            to: item.number,
            from,
            text: item.message,
          });
        });
        Promise.allSettled(listPromises)
          .then((responses) => {
            resolve(responses);
          })
          .catch((error) => {
            reject(error);
          });
      } catch (error) {
        reject(error);
      }
    });
  }
}
