import { NextResponse } from "next/server";
import { z } from "zod";

import { sendContactEmail } from "~/server/mail";

const contactSchema = z.object({
  name: z.string().trim().min(1, "Please enter your name").max(200),
  email: z.string().trim().email("Please enter a valid email").max(320),
  company: z.string().trim().max(200).optional(),
  message: z
    .string()
    .trim()
    .min(10, "Tell me a little more about what you need")
    .max(5000),
  // A honeypot. It is hidden from real users and tempting to bots. Humans leave it empty.
  website: z.string().optional(),
});

export async function POST(req: Request) {
  const body: unknown = await req.json().catch(() => null);
  const parsed = contactSchema.safeParse(body);

  if (!parsed.success) {
    return NextResponse.json(
      {
        ok: false,
        message: "Please correct the highlighted fields.",
        fieldErrors: parsed.error.flatten().fieldErrors,
      },
      { status: 400 },
    );
  }

  if (parsed.data.website && parsed.data.website.length > 0) {
    return NextResponse.json({ ok: true });
  }

  try {
    await sendContactEmail({
      name: parsed.data.name,
      email: parsed.data.email,
      company: parsed.data.company ?? null,
      message: parsed.data.message,
    });

    return NextResponse.json({ ok: true });
  } catch (err) {
    console.error("[contact] failed to send email:", err);
    return NextResponse.json(
      { ok: false, message: "Could not send your message. Please try again." },
      { status: 500 },
    );
  }
}
