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

const HCAPTCHA_SECRET = process.env.HCAPTCHA_SECRET ?? '';
const SHARED_API_KEY = process.env.SHARED_API_KEY ?? '';

export async function POST(req: NextRequest) {
    try {
        const body = await req.json();
        const origin = req.headers.get("origin") || "http://localhost:3000";
        const captchaToken = body.captcha;

        if (!captchaToken) {
            return NextResponse.json({success: false, error: 'Captcha is required'}, {status: 400});
        }

        // Step 1: Verify hCaptcha token with their API
        const verifyResponse = await fetch('https://api.hcaptcha.com/siteverify', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: new URLSearchParams({
                secret: HCAPTCHA_SECRET,
                response: captchaToken,
            }),
        });

        const captchaResult = await verifyResponse.json();

        if (!captchaResult.success) {
            return NextResponse.json({success: false, error: 'Captcha verification failed'}, {status: 403});
        }

        // Step 2: Forward valid contact request to Spring Boot backend
        const backendRes = await fetch('http://localhost:8080/api/contact', {
            method: 'POST',
            headers: {
                "Origin": origin,
                'Content-Type': 'application/json',
                'X-Frontend-Key': SHARED_API_KEY,
            },
            body: JSON.stringify(body),
        });

        const backendText = await backendRes.text();

        if (!backendRes.ok) {
            return NextResponse.json({success: false, error: backendText}, {status: backendRes.status});
        }

        return NextResponse.json({success: true, message: backendText});
    } catch (err: any) {
        console.error('[ContactAPI] error:', err);
        return NextResponse.json({success: false, error: err.message}, {status: 500});
    }
}
