import { NextResponse } from "next/server";
import { z } from "zod";
import { sendContactEmail } from "@/lib/email/send";
import { logger } from "@/lib/logger";

const contactSchema = z.object({
  name: z.string().min(1).max(200),
  email: z.string().email(),
  subject: z.string().min(1).max(300),
  message: z.string().min(10).max(5000),
});

export async function POST(request: Request) {
  let body: unknown;
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
  }

  const parsed = contactSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json(
      { error: "Invalid input", details: parsed.error.flatten() },
      { status: 422 },
    );
  }

  const { name, email, subject, message } = parsed.data;

  logger.info({ action: 'contact_form_submitted' }, 'Contact form submitted');

  try {
    await sendContactEmail({ name, email, subject, message });
  } catch {
    // Logged in sendContactEmail; still return 200 to avoid leaking internals
  }

  return NextResponse.json({ ok: true });
}
