import { Router } from "express";
import Mail from "../models/Mail";
import nodemailer from "nodemailer";

const router = Router();

router.post("/", async (req, res) => {
  try {
    const referer = req.headers.referer;
    const { fullname, email, phone, request } = req.body;

    await Mail.create({ fullname, email, phone, request, referer });

    // create reusable transporter object using the default SMTP transport
    let transporter = nodemailer.createTransport({
      host: "mail.netangels.ru",
      port: 587,
      secure: false, // true for 465, false for other ports
      auth: {
        user: "test@graff.tech", // generated ethereal user
        pass: "ZmL0pKiDFWUyCDMq", // generated ethereal password
      },
    });

    // send mail with defined transport object
    let info = await transporter.sendMail({
      from: email, // sender address
      to: "info@graff.tech", // list of receivers
      subject: "Заявка с сайта graff.estate", // Subject line
      text: `
      Имя Фамилия: ${fullname}
      Email: ${email}
      Телефон: ${phone}
      Текст запроса: ${request}
    `, // plain text body
      html: `<div>
      <p>Имя: ${fullname}</p>
      <p>Email: ${email}</p>
      <p>Телефон: ${phone}</p>
      <p>Текст запроса: ${request}</p>
    </div>`, // html body
    });

    console.log(info);

    console.log(req.body);

    res.json({ ok: 1 });
  } catch (error) {
    console.log(error);
    res.json({ error: 1 });
  }
});

const mailRoute = router;

export default mailRoute;
