import { NextResponse } from "next/server";
import { contactBodySchema, isHoneypotTriggered, sanitizeHeaderValue } from "@/lib/contact";
import { getResend } from "@/lib/email";

export async function POST(request: Request) {
  const FORMS_ENABLED = process.env.FORMS_ENABLED !== "false";
  if (!FORMS_ENABLED) {
    return NextResponse.json(
      { ok: false, error: "disabled" },
      { status: 503 }
    );
  }


  const contentType = request.headers.get("content-type");
  if (contentType !== "application/json") {
    return NextResponse.json(
      { ok: false, error: "validation" },
      { status: 400 }
    );
  }

  const siteUrl = process.env.NEXT_PUBLIC_SITE_URL;
  if (siteUrl) {
    const origin = request.headers.get("origin");
    if (origin) {
      const expectedOrigin = new URL(siteUrl).origin;
      if (origin !== expectedOrigin) {
        return NextResponse.json(
          { ok: false, error: "forbidden" },
          { status: 403 }
        );
      }
    }
  }

  let parsed: Record<string, string | undefined>;
  try {
    parsed = await request.json();
  } catch {
    return NextResponse.json(
      { ok: false, error: "validation" },
      { status: 400 }
    );
  }

  const validated = contactBodySchema.safeParse(parsed);
  if (!validated.success) {
    return NextResponse.json(
      {
        ok: false,
        error: "validation",
        issues: validated.error.issues.map((i) => i.message),
      },
      { status: 400 }
    );
  }

  if (isHoneypotTriggered({ website: parsed.website, company: parsed.company })) {
    return NextResponse.json({ ok: true }, { status: 200 });
  }

  const { name, email, topic, message, phone } = validated.data;

  const sanitizedName = sanitizeHeaderValue(name);
  const sanitizedEmail = sanitizeHeaderValue(email);
  const sanitizedTopic = sanitizeHeaderValue(topic);
  const sanitizedPhone = phone ? sanitizeHeaderValue(phone) : "";
  const sanitizedMessage = message.replace(/[\r\n]+/g, " ").trim();

  const subject = `New inquiry: ${sanitizedTopic}`;
  const from = `Jenado Unlimited <onboarding@resend.dev>`;
  const toEmail = process.env.RESEND_EMAIL || "hello@jenadounlimited.com";

  try {
    await getResend().emails.send({
      from,
      to: toEmail,
      subject,
      text: `Name: ${sanitizedName}
Email: ${sanitizedEmail}
Phone: ${sanitizedPhone}
Topic: ${sanitizedTopic}

Message:
${sanitizedMessage}`,
    });

    return NextResponse.json({ ok: true }, { status: 200 });
  } catch {
    return NextResponse.json(
      { ok: false, error: "server" },
      { status: 500 }
    );
  }
}
