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

function getSettings() {
  return {
    host:      process.env.MAIL_HOST ?? "nicht gesetzt",
    port:      process.env.MAIL_PORT ?? "465",
    scheme:    process.env.MAIL_SECURE === "true" ? "smtps" : "smtp",
    username:  maskEmail(process.env.MAIL_USER ?? ""),
    password:  process.env.MAIL_PASS ? "gesetzt" : "fehlt",
    from:      `${process.env.MAIL_FROM_NAME ?? "Toolaro"} <${process.env.MAIL_FROM ?? ""}>`,
    reply_to:  process.env.MAIL_REPLY_TO ?? "",
  };
}

function maskEmail(value: string): string {
  if (!value) return "fehlt";
  if (!value.includes("@")) return "*".repeat(Math.max(4, Math.min(12, value.length)));
  const [local, domain] = value.split("@");
  return local.slice(0, 2) + "*".repeat(Math.max(3, local.length - 2)) + "@" + domain;
}

export async function GET() {
  if (process.env.MAIL_TEST_ENABLED !== "true") {
    return NextResponse.json({ ok: false }, { status: 404 });
  }
  return NextResponse.json({ ok: true, settings: getSettings(), defaultTo: process.env.MAIL_TEST_TO ?? "" });
}

export async function POST(request: Request) {
  if (process.env.MAIL_TEST_ENABLED !== "true") {
    return NextResponse.json({ ok: false }, { status: 404 });
  }

  try {
    const body = (await request.json()) as { to?: string; subject?: string; message?: string };
    const to      = String(body.to      ?? "").trim();
    const subject = String(body.subject ?? "").trim();
    const message = String(body.message ?? "").trim();

    if (!to || !subject || !message) {
      return NextResponse.json({ ok: false, error: "Fehlende Felder." }, { status: 400 });
    }

    const settings = getSettings();
    const html = `<!DOCTYPE html>
<html lang="de"><head><meta charset="UTF-8"><title>Mail-Test</title></head>
<body style="font-family:Arial;color:#0f172a;line-height:1.6;">
  <h1 style="font-size:22px;">Toolaro Mail-Test</h1>
  <p style="white-space:pre-line;">${message.replace(/&/g,"&amp;").replace(/</g,"&lt;")}</p>
  <h2 style="font-size:16px;margin-top:28px;">Konfiguration</h2>
  <ul>${Object.entries(settings).map(([k,v])=>`<li><strong>${k}:</strong> ${v}</li>`).join("")}</ul>
  <p style="font-size:12px;color:#64748b;">Wenn diese Mail angekommen ist, funktioniert der SMTP-Versand.</p>
</body></html>`;

    const transporter = nodemailer.createTransport({
      host: process.env.MAIL_HOST,
      port: Number(process.env.MAIL_PORT ?? 465),
      secure: process.env.MAIL_SECURE === "true",
      auth: { user: process.env.MAIL_USER, pass: process.env.MAIL_PASS },
    });

    const started = Date.now();
    await transporter.sendMail({
      from: `"${process.env.MAIL_FROM_NAME ?? "Toolaro"}" <${process.env.MAIL_FROM}>`,
      to,
      subject: `[Mail-Test] ${subject}`,
      html,
      text: message,
    });
    const ms = Date.now() - started;

    return NextResponse.json({ ok: true, ms });
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    return NextResponse.json({ ok: false, error: msg }, { status: 500 });
  }
}
