import { Resend } from "resend";
import type { NextRequest } from "next/server";
import { prisma } from "@/lib/db";

const resend = new Resend(process.env.RESEND_API_KEY);

export async function POST(req: NextRequest) {
  try {
    const { name, email, subject, message } = await req.json();

    if (!name || !email || !message) {
      return Response.json({ error: "Missing required fields" }, { status: 400 });
    }

    await prisma.contactMessage.create({
      data: { name, email, subject: subject ?? null, message },
    });

    if (process.env.RESEND_API_KEY) {
      await resend.emails.send({
        from: "biztaghavi.com <noreply@biztaghavi.com>",
        to: [process.env.CONTACT_EMAIL ?? "ali@biztaghavi.com"],
        replyTo: email,
        subject: subject ? `[biztaghavi.com] ${subject}` : `[biztaghavi.com] پیام از ${name}`,
        text: `نام: ${name}\nایمیل: ${email}\n\n${message}`,
        html: `
          <div style="font-family: sans-serif; max-width: 600px;">
            <p><strong>نام:</strong> ${name}</p>
            <p><strong>ایمیل:</strong> ${email}</p>
            ${subject ? `<p><strong>موضوع:</strong> ${subject}</p>` : ""}
            <hr />
            <p style="white-space: pre-wrap;">${message}</p>
          </div>
        `,
      });
    }

    return Response.json({ success: true });
  } catch (err) {
    console.error("[contact]", err);
    return Response.json({ error: "Failed to send" }, { status: 500 });
  }
}
