import type { APIRoute } from "astro";

// Your Cloudflare Turnstile Secret Key
// In production, this should be set in environment variables
const TURNSTILE_SECRET_KEY = import.meta.env.CF_TURNSTILE_SECRET_KEY || import.meta.env.TURNSTILE_SECRET_KEY;
// The n8n webhook URL
const WEBHOOK_URL = import.meta.env.N8N_WEBHOOK_URL || "https://n8n.anlstudio.cc/webhook/contact";

export const POST: APIRoute = async ({ request }) => {
    try {
        const body = await request.json();
        const { name, phone, email, message, "cf-turnstile-response": token } = body;

        // Basic validation
        if (!name || !phone || !email || !message) {
            return new Response(JSON.stringify({ error: "Missing required fields" }), {
                status: 400,
                headers: { "Content-Type": "application/json" },
            });
        }

        if (!token) {
            return new Response(JSON.stringify({ error: "[Turnstile] No token provided" }), {
                status: 400,
                headers: { "Content-Type": "application/json" },
            });
        }

        // Verify Turnstile token
        if (TURNSTILE_SECRET_KEY) {
            const turnstileVerify = await fetch(
                "https://challenges.cloudflare.com/turnstile/v0/siteverify",
                {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded",
                    },
                    body: new URLSearchParams({
                        secret: TURNSTILE_SECRET_KEY,
                        response: token,
                    }).toString(),
                }
            );

            const turnstileResult = await turnstileVerify.json();

            if (!turnstileResult.success) {
                return new Response(JSON.stringify({ error: "[Turnstile] Token verification failed" }), {
                    status: 400,
                    headers: { "Content-Type": "application/json" },
                });
            }
        } else {
            console.warn("TURNSTILE_SECRET_KEY is not defined. Skipping verification.");
        }

        // After successful verification, send data to n8n
        const n8nResponse = await fetch(WEBHOOK_URL, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({ name, phone, email, message }),
        });

        if (!n8nResponse.ok) {
            throw new Error(`n8n webhook failed with status ${n8nResponse.status}`);
        }

        return new Response(JSON.stringify({ success: true }), {
            status: 200,
            headers: { "Content-Type": "application/json" },
        });

    } catch (error) {
        console.error("API proxy error:", error);
        return new Response(JSON.stringify({ error: "Internal server error" }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
        });
    }
};
