import { NextResponse } from "next/server";
import { insert, now } from "@/lib/db";
import { verifyRecaptcha } from "@/lib/recaptcha";

export const runtime = "nodejs";

export async function POST(request: Request) {
  const data = await request.formData();
  const get = (k: string) => (typeof data.get(k) === "string" ? String(data.get(k)) : "");

  const token = get("token");
  const ok = await verifyRecaptcha(token);
  if (!ok) return NextResponse.redirect(new URL("/", request.url), 303);

  const name = get("name");
  const lName = get("l_name");
  const email = get("email");
  const phone = get("phone_no");
  const subject = get("subject");
  const comment = get("comment");

  await insert("contact", {
    name,
    l_name: lName,
    email,
    phone_no: phone,
    subject,
    comment,
    sent_status: 0,
    updated_at: now(),
  });

  const hremail = "sales@paramvirpower.com";
  const mailcontent = `Hello,<br><br>${comment}<br><br> Username: ${name}${lName}<br>EMail: ${email}<br>Mo. ${phone}<br><br> Thanks, <br>Paramvir Power Solutions LLP <br><br><span style="color:red"> This is an automated mail. Please do not reply to this email.</span>`;
  await insert("email", {
    from_email: email,
    from_name: name,
    to_email: hremail,
    to_name: "",
    title: subject,
    subject: `${subject} PPSL - Inquiry`,
    content: mailcontent,
    date: now(),
  });

  return NextResponse.redirect(new URL("/thank-you", request.url), 303);
}
