
import { NextRequest, NextResponse } from "next/server";

export async function POST(request: NextRequest) {
    try {
        const body = await request.json();

        const {
            name,
            email,
            phone,
            subject,
            message,
            captchaToken,
        } = body;
        if (!captchaToken) {
            return NextResponse.json(
                {
                    success: false,
                    message:
                        "Please complete the reCAPTCHA verification.",
                },
                { status: 400 }
            );
        }
        const secretKey =
            process.env.RECAPTCHA_SECRET_KEY;

        if (!secretKey) {
            console.error(
                "RECAPTCHA_SECRET_KEY is missing"
            );

            return NextResponse.json(
                {
                    success: false,
                    message:
                        "reCAPTCHA server configuration error.",
                },
                { status: 500 }
            );
        }
        const params = new URLSearchParams();

        params.append("secret", secretKey);
        params.append("response", captchaToken);

        const googleResponse = await fetch(
            "https://www.google.com/recaptcha/api/siteverify",
            {
                method: "POST",
                headers: {
                    "Content-Type":
                        "application/x-www-form-urlencoded",
                },
                body: params.toString(),
                cache: "no-store",
            }
        );

        const captchaResult =
            await googleResponse.json();


        if (!captchaResult.success) {
            return NextResponse.json(
                {
                    success: false,
                    message:
                        "reCAPTCHA verification failed.",
                    errors:
                        captchaResult["error-codes"] || [],
                },
                { status: 400 }
            );
        }
        return NextResponse.json({
            success: true,
            message:
                "Enquiry submitted successfully.",
        });
    } catch (error) {
        console.error(
            "Contact enquiry error:",
            error
        );

        return NextResponse.json(
            {
                success: false,
                message:
                    "Internal Server Error",
            },
            { status: 500 }
        );
    }
}