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

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const { host, port, user, password, secure, from, to, subject } = body;

    if (!host || !port) {
      return NextResponse.json({ error: "host and port are required" }, { status: 400 });
    }

    const transporter = nodemailer.createTransport({
      host,
      port: Number(port),
      secure: secure === true || secure === "true" || Number(port) === 465,
      auth: user ? { user, pass: password ?? "" } : undefined,
      connectionTimeout: 10000,
      greetingTimeout: 8000,
      socketTimeout: 10000,
      tls: { rejectUnauthorized: false },
    });

    // Verify connection
    await transporter.verify();

    // Optionally send test email
    let messageId = null;
    if (from && to) {
      const info = await transporter.sendMail({
        from,
        to,
        subject: subject ?? "SMTP Test — Seakses Tools",
        text: `This is a test email sent from Seakses Tools SMTP Mailer Test.\n\nServer: ${host}:${port}\nTime: ${new Date().toISOString()}`,
        html: `<p>This is a test email sent from <strong>Seakses Tools</strong> SMTP Mailer Test.</p><p>Server: <code>${host}:${port}</code><br>Time: ${new Date().toISOString()}</p>`,
      });
      messageId = info.messageId;
    }

    return NextResponse.json({
      success: true,
      message: from && to ? `Connection verified and test email sent to ${to}` : "SMTP connection verified successfully",
      messageId,
      host,
      port: Number(port),
    });
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : "SMTP error";
    return NextResponse.json({ success: false, error: msg }, { status: 200 });
  }
}
