import { NextResponse } from "next/server";
import { addContactInquiry } from "@/lib/admin/store";
import { sendContactInquiryMail } from "@/lib/mail/smtp";

function text(value: FormDataEntryValue | null) {
  return typeof value === "string" ? value.trim() : "";
}

export async function POST(request: Request) {
  const form = await request.formData();
  const name = text(form.get("name"));
  const email = text(form.get("email"));
  const subject = text(form.get("subject"));
  const message = text(form.get("message"));

  if (!name || !email.includes("@") || !subject || message.length < 10 || form.get("privacyAccepted") !== "on") {
    return NextResponse.json({ message: "Bitte füllen Sie alle Pflichtfelder aus." }, { status: 400 });
  }

  const inquiry = await addContactInquiry(form);
  await sendContactInquiryMail(inquiry);

  return NextResponse.json({
    message: "Ihre Nachricht wurde erfasst. Sie erhalten eine Rückmeldung.",
  });
}
