import nodemailer from 'nodemailer';
import { getEnv } from './env';
import type { ContactData } from './contact';

export async function sendContactEmail(data: ContactData): Promise<void> {
  const transporter = nodemailer.createTransport({
    host: getEnv('SMTP_HOST'),
    port: Number(getEnv('SMTP_PORT', '587')),
    secure: Number(getEnv('SMTP_PORT', '587')) === 465,
    auth: { user: getEnv('SMTP_USER'), pass: getEnv('SMTP_PASS') },
  });
  await transporter.sendMail({
    from: getEnv('CONTACT_FROM'),
    to: getEnv('CONTACT_TO', 'info@insanitylab.it'),
    replyTo: data.email,
    subject: `Nuovo contatto dal sito: ${data.firstName} ${data.lastName}`.trim(),
    text: [
      `Nome: ${data.firstName} ${data.lastName}`.trim(),
      data.phone && `Telefono: ${data.phone}`,
      `E-mail: ${data.email}`,
      '',
      data.message,
    ].filter(Boolean).join('\n'),
  });
}
