const PhoneVerifications = require("../models/PhoneVerifications");
const fs = require("fs");
const path = require("path");

exports.create = (req, res, next) => {
  const { phone_verification_signature, data } = req.body;
  const { client_name, email_address, mobile_number, company_name } = data;

  const encoded = phone_verification_signature;

  const base64ToArray = encoded.split(";base64,");
  const extension = "png";

  const imageData = base64ToArray[1];
  const fileName = ((new Date().getTime() / 1000) | 0) + "." + extension;

  const uploadPath = `${__dirname}/../../public_html/uploads/phone-verification/`;
  const imagePath = path.join(uploadPath) + fileName;

  fs.writeFileSync(imagePath, imageData, { encoding: "base64" });

  PhoneVerifications.findOne({
    where: {
      company_name,
      mobile_number,
    },
  })
    .then((response) => {
      if (response) throw new Error("Mobile number already exists in the company");

      return PhoneVerifications.create({
        client_name,
        company_name,
        email_address,
        mobile_number,
        signature: fileName,
      });
    })
    .then((createdResponse) => {
      res.status(200).json({ success: true, record: createdResponse });
    })
    .catch((err) => {
      next(err);
    });
};
