import nodemailer from 'nodemailer';
import { TBaseForm } from '@shared/api/api.types';
import { CORE } from '@shared/config/core';

async function sendMail(data: TBaseForm) {
  const { name, phone, message, form } = data;

  const formattedBody = `
    <html lang="ru-RU">
      <body>
        <p>Сообщение с сайта "Оценка-Сочи"</p>
        <p>Форма отправки: ${form}</p>
        <p>Имя отправителя: ${name ?? 'не указано'}</p>
        <p>Номер телефона: ${phone}</p>
        <p>Сообщение: ${message ?? 'отсутствует'}</p>
      </body>
    </html>
  `;

  const transporter = nodemailer.createTransport({
    service: 'Yandex',
    auth: {
      user: CORE.MAIL_USER,
      pass: CORE.MAIL_PASS,
    },
  });

  return await transporter.sendMail({
    from: CORE.MAIL_FROM,
    to: CORE.MAIL_TO,
    subject: 'Заявка с сайта Ocenka-Sochi',
    html: formattedBody,
  });
}

export async function POST(request: Request) {
  try {
    const payload = await request.json();

    if (payload.secure !== CORE.MAIL_SECURE_KEY) {
      await Promise.reject('Request failure!');
    }

    const sendResult = await sendMail({ ...payload });

    const data = { message: 'Form accepted' };
    const headers = new Headers({
      'Content-Type': 'application/json',
    });
    const options = {
      status: 200,
      statusText: 'OK',
      headers: headers,
    };

    if (sendResult?.messageId) {
      return new Response(JSON.stringify(data), options);
    } else {
      await Promise.reject('Sending request failure!');
    }
  } catch (error) {
    return new Response(`Api error: ${error}`, {
      status: 400,
    });
  }
}
