import dbConnect from "@/lib/mongodb";
import Contact from "@/models/Contact";
import { NextRequest, NextResponse } from "next/server";
import { sendTemplateMail } from "@/lib/email";
import GeneralSettings from "@/models/GeneralSettings";

export async function POST(request: NextRequest) {
  try {
    await dbConnect();
    const body = await request.json();
    const { name, email, phone, message } = body;
    if (!name || !email || !phone || !message) {
      return NextResponse.json(
        { success: false, error: "Missing required fields" },
        { status: 400 },
      );
    }
    const contact = new Contact({ name, email, phone, message });
    await contact.save();
    const admindetails = await GeneralSettings.findOne();
    try {
      await sendTemplateMail({
        slug: "contact-us",
        to: email,
        replyTo: email,
        templateData: { name, email, phone, message },
      });
      await sendTemplateMail({
        slug: "admin-contact",
        to: admindetails.email,
        replyTo: admindetails.email,
        templateData: { name, email, phone, message },
      });
    } catch (err: any) {
      console.error("Contact notification email failed", err);
    }

    return NextResponse.json({ success: true, data: contact });
  } catch (err: any) {
    console.error("Contact POST error", err);
    return NextResponse.json(
      { success: false, error: err.message || "Failed to submit contact form" },
      { status: 500 },
    );
  }
}
