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

import { sendMail } from "@/lib/mailer";
import { verifyPublicCaptcha } from "@/lib/public-captcha";

const contactAdminSchema = z.object({
  name: z.string().trim().min(2, "Nama wajib diisi"),
  email: z.string().trim().email("Email tidak valid"),
  message: z.string().trim().min(10, "Pesan minimal 10 karakter"),
  captcha_token: z.string().trim().min(1, "CAPTCHA token tidak valid"),
  captcha_answer: z.coerce.number(),
  website: z.string().optional()
});

export async function POST(request: Request) {
  try {
    const parsed = contactAdminSchema.safeParse(await request.json());
    if (!parsed.success) {
      return NextResponse.json(
        {
          message: "Validasi gagal",
          errors: parsed.error.flatten().fieldErrors
        },
        { status: 422 }
      );
    }

    if (parsed.data.website && parsed.data.website.trim() !== "") {
      return NextResponse.json({ message: "Pesan berhasil dikirim." });
    }

    const captchaOk = verifyPublicCaptcha(
      parsed.data.captcha_token,
      parsed.data.captcha_answer
    );

    if (!captchaOk) {
      return NextResponse.json(
        {
          message: "Verifikasi CAPTCHA gagal. Muat ulang halaman dan coba lagi."
        },
        { status: 400 }
      );
    }

    await sendMail({
      to: "wirabasalamah@gmail.com",
      subject: `[AbelBirdnest] Permintaan bantuan login dari ${parsed.data.name}`,
      text: `Nama: ${parsed.data.name}\nEmail: ${parsed.data.email}\n\nPesan:\n${parsed.data.message}`,
      html: `
        <p><strong>Nama:</strong> ${parsed.data.name}</p>
        <p><strong>Email:</strong> ${parsed.data.email}</p>
        <p><strong>Pesan:</strong></p>
        <p>${parsed.data.message.replace(/\n/g, "<br />")}</p>
      `
    });

    return NextResponse.json({
      message: "Pesan berhasil dikirim ke admin."
    });
  } catch (error) {
    return NextResponse.json(
      {
        message: error instanceof Error ? error.message : "Gagal mengirim pesan ke admin"
      },
      { status: 500 }
    );
  }
}
