import { NextResponse } from "next/server";
import { requireAdminSession } from "@/lib/admin/auth";
import { saveSmtpSettings, toPublicSmtpSettings } from "@/lib/mail/config";
import { sendTestMail } from "@/lib/mail/smtp";

export async function POST(request: Request) {
  if (!await requireAdminSession()) return NextResponse.json({ message: "Nicht autorisiert." }, { status: 401 });
  const form = await request.formData();
  const action = String(form.get("action") ?? "save");

  if (action === "test") {
    const settings = await saveSmtpSettings(form);
    const result = await sendTestMail();
    return NextResponse.json({
      message: result.ok ? "Test-E-Mail wurde gesendet." : result.error ?? "Test-E-Mail fehlgeschlagen.",
      ok: result.ok,
      settings: toPublicSmtpSettings(settings),
    }, { status: result.ok ? 200 : 400 });
  }

  const settings = await saveSmtpSettings(form);
  return NextResponse.json({
    message: "SMTP-Konfiguration gespeichert.",
    settings: toPublicSmtpSettings(settings),
  });
}
