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

function required(value: FormDataEntryValue | null) {
  return typeof value === "string" && value.trim().length > 0;
}

export async function POST(request: Request) {
  const form = await request.formData();
  const name = form.get("name");
  const email = form.get("email");
  const manufacturer = form.get("manufacturer");
  const model = form.get("model");
  const deviceType = form.get("deviceType");
  const description = form.get("description");
  const privacyAccepted = form.get("privacyAccepted");

  if (!required(name) || !required(email) || !required(manufacturer) || !required(model) || !required(deviceType) || !required(description) || privacyAccepted !== "on") {
    return NextResponse.json({ message: "Bitte füllen Sie alle Pflichtfelder aus." }, { status: 400 });
  }

  const inquiry = await addRepairInquiry(form);
  await sendRepairInquiryMail(inquiry);

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