import { NextResponse } from 'next/server';
import nodemailer from 'nodemailer';
import { env } from '@/lib/env';

export const runtime = 'nodejs';

const escapeHtml = (value: string) =>
  value
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');

const stripHeaderBreaks = (value: string) => value.replace(/[\r\n]+/g, ' ').trim();

const isValidEmail = (value: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { name, email, subject, message } = body;

    if (
      typeof name !== 'string' ||
      typeof email !== 'string' ||
      typeof message !== 'string' ||
      !name.trim() ||
      !email.trim() ||
      !message.trim() ||
      !isValidEmail(email.trim())
    ) {
      return NextResponse.json(
        { error: 'Valid name, email, and message are required.' },
        { status: 400 }
      );
    }

    const cleanName = stripHeaderBreaks(name);
    const cleanEmail = stripHeaderBreaks(email);
    const cleanSubject = typeof subject === 'string' ? stripHeaderBreaks(subject) : '';
    const cleanMessage = message.trim();
    const useTls = (process.env.EMAIL_USE_TLS || process.env.SMTP_USE_TLS || 'true').toLowerCase() === 'true';
    const smtpHost = process.env.SMTP_HOST;
    const smtpUser = process.env.SMTP_USER;
    const smtpPassword = process.env.SMTP_PASSWORD;

    if (!smtpHost || !smtpUser || !smtpPassword) {
      console.error('SMTP configuration is incomplete.');
      return NextResponse.json(
        { error: 'Email service is not configured.' },
        { status: 500 }
      );
    }

    // Configure the transporter with SMTP credentials
    const transporter = nodemailer.createTransport({
      host: smtpHost,
      port: Number(process.env.SMTP_PORT) || 587,
      secure: Number(process.env.SMTP_PORT) === 465, // Implicit TLS
      requireTLS: useTls, // Explicit TLS via STARTTLS
      auth: {
        user: smtpUser,
        pass: smtpPassword,
      },
    });

    const emailFrom = process.env.CONTACT_EMAIL || smtpUser;

    // Email content
    const mailOptions = {
      from: { name: cleanName, address: smtpUser }, // Sender address must match authenticated user
      replyTo: cleanEmail, // Set the reply-to to the user's email so you can reply to them directly
      to: emailFrom || env.supportEmail, // List of receivers (support email or fallback)
      subject: cleanSubject || `New Contact Form Submission from ${cleanName}`, // Subject line
      text: `Name: ${cleanName}\nEmail: ${cleanEmail}\n\nMessage:\n${cleanMessage}`, // Plain text body
      html: `
        <h3>New Contact Form Submission</h3>
        <p><strong>Name:</strong> ${escapeHtml(cleanName)}</p>
        <p><strong>Email:</strong> ${escapeHtml(cleanEmail)}</p>
        <p><strong>Subject:</strong> ${escapeHtml(cleanSubject || 'N/A')}</p>
        <br/>
        <p><strong>Message:</strong></p>
        <p>${escapeHtml(cleanMessage).replace(/\n/g, '<br/>')}</p>
      `, // HTML body
    };

    // Send the email
    const info = await transporter.sendMail(mailOptions);
    console.log('Message sent: %s', info.messageId);

    return NextResponse.json({ success: true, message: 'Message sent successfully.' }, { status: 200 });
  } catch (error) {
    console.error('Error sending email:', error);
    return NextResponse.json(
      { error: 'Failed to send message. Please try again later.' },
      { status: 500 }
    );
  }
}
