import { NextResponse } from "next/server";
import nodemailer from "nodemailer";

export const runtime = "nodejs";

const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

const escapeHtml = (value: string) =>
  value.replace(/[&<>"']/g, (char) => {
    const map: Record<string, string> = {
      "&": "&amp;",
      "<": "&lt;",
      ">": "&gt;",
      '"': "&quot;",
      "'": "&#39;"
    };
    return map[char] || char;
  });

const isConfigured = () =>
  Boolean(
    process.env.SMTP_HOST &&
      process.env.SMTP_PORT &&
      process.env.SMTP_USER &&
      process.env.SMTP_PASS
  );

export async function POST(request: Request) {
  let payload: {
    fullName?: string;
    email?: string;
    company?: string;
    objective?: string;
    message?: string;
    companySite?: string;
  } | null = null;

  try {
    payload = await request.json();
  } catch {
    return NextResponse.json({ error: "Invalid request payload." }, { status: 400 });
  }

  if (!payload) {
    return NextResponse.json({ error: "Invalid request payload." }, { status: 400 });
  }

  if (payload.companySite) {
    return NextResponse.json({ ok: true });
  }

  const fullName = (payload.fullName || "").trim();
  const email = (payload.email || "").trim();
  const company = (payload.company || "").trim();
  const objective = (payload.objective || "").trim();
  const message = (payload.message || "").trim();

  if (!fullName || !email || !company || !objective) {
    return NextResponse.json({ error: "Missing required fields." }, { status: 400 });
  }

  if (!emailPattern.test(email)) {
    return NextResponse.json({ error: "Invalid email address." }, { status: 400 });
  }

  if (!isConfigured()) {
    return NextResponse.json(
      { error: "Email service is not configured." },
      { status: 500 }
    );
  }

  const port = Number(process.env.SMTP_PORT || "587");
  const secure = process.env.SMTP_SECURE === "true" || port === 465;


  const transporter = nodemailer.createTransport({
    host: process.env.SMTP_HOST,
    port,
    secure,
    auth: {
      user: process.env.SMTP_USER,
      pass: process.env.SMTP_PASS
    },
    // Add timeout and connection settings
    connectionTimeout: 10000, // 10 seconds
    greetingTimeout: 5000,    // 5 seconds
    socketTimeout: 10000,     // 10 seconds
    // Add TLS options for better compatibility
    tls: {
      rejectUnauthorized: false, // Allow self-signed certificates
      ciphers: 'SSLv3'
    },
    // Add debug logging
    debug: process.env.NODE_ENV !== 'production',
    logger: process.env.NODE_ENV !== 'production'
  });

  const to = process.env.CONTACT_TO || "hello@optrl.com";
  const from =
    process.env.SMTP_FROM || `OptRL Contact <${process.env.SMTP_USER}>`;

  const text = [
    "New contact request",
    `Name: ${fullName}`,
    `Email: ${email}`,
    `Company: ${company}`,
    `Objective: ${objective}`,
    `Message: ${message || "Not provided"}`,
    `Sent: ${new Date().toISOString()}`
  ].join("\\n");

  const html = `
    <h2>New contact request</h2>
    <p><strong>Name:</strong> ${escapeHtml(fullName)}</p>
    <p><strong>Email:</strong> ${escapeHtml(email)}</p>
    <p><strong>Company:</strong> ${escapeHtml(company)}</p>
    <p><strong>Objective:</strong> ${escapeHtml(objective)}</p>
    <p><strong>Message:</strong><br />${escapeHtml(message || "Not provided")}</p>
    <p><strong>Sent:</strong> ${escapeHtml(new Date().toISOString())}</p>
  `;

  try {
    // Test connection first
    console.log('Testing SMTP connection...');
    await transporter.verify();
    console.log('SMTP connection verified successfully');

    // Send the email
    console.log('Sending email...');
    const result = await transporter.sendMail({
      from,
      to,
      replyTo: email,
      subject: `OptRL - A new inquiry from your website - ${fullName}`,
      text,
      html,
    });
    console.log('Email sent successfully:', result.messageId);
  } catch (error: any) {
    // Provide more specific error messages
    let errorMessage = "Unable to send your message right now.";
    if (error.code === 'ETIMEDOUT') {
      errorMessage = "Email service timeout. Please try again later.";
    } else if (error.code === 'ECONNREFUSED') {
      errorMessage = "Email service unavailable. Please try again later.";
    } else if (error.code === 'EAUTH') {
      errorMessage = "Email service authentication failed.";
    }
    
    return NextResponse.json(
      { error: errorMessage },
      { status: 500 }
    );
  }

  return NextResponse.json({ ok: true });
}
