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

export async function POST(req: NextRequest) {
    const {captcha, ...data} = await req.json();
    const {name, email, company, phone, website, message} = data;

    const isDev = process.env.NODE_ENV === "development";
    const hCaptchaSecret = isDev
        ? "0x0000000000000000000000000000000000000000" // hCaptcha test secret
        : "ES_ff59a664dc764f92870bf2c7b4eab7c5";

    // ✅ hCaptcha verification
    const captchaRes = await fetch("https://hcaptcha.com/siteverify", {
        method: "POST",
        headers: {"Content-Type": "application/x-www-form-urlencoded"},
        body: `response=${captcha}&secret=${hCaptchaSecret}`,
    });

    const captchaResult = await captchaRes.json();
    if (!captchaResult.success) {
        return NextResponse.json({success: false, error: "CAPTCHA-Verifizierung fehlgeschlagen."}, {status: 403});
    }

    // ✅ Send mail with Ethereal (for dev) or real SMTP later
    const testAccount = await nodemailer.createTestAccount();
    const transporter = nodemailer.createTransport({
        host: testAccount.smtp.host,
        port: testAccount.smtp.port,
        secure: testAccount.smtp.secure,
        auth: {
            user: testAccount.user,
            pass: testAccount.pass,
        },
    });

    const mailToMe = {
        from: email,
        to: "thatsaphorn@outlook.de",
        subject: "Neue Nachricht vom Kontaktformular",
        html: `
            <p><strong>Name:</strong> ${name}</p>
            <p><strong>E-Mail:</strong> ${email}</p>
            <p><strong>Firma:</strong> ${company || "—"}</p>
            <p><strong>Telefon:</strong> ${phone || "—"}</p>
            <p><strong>Webseite:</strong> ${website || "—"}</p>
            <p><strong>Nachricht:</strong></p>
            <p>${message}</p>
        `,
    };

    try {
        const info = await transporter.sendMail(mailToMe);

        return NextResponse.json({
            success: true,
            previewUrl: nodemailer.getTestMessageUrl(info),
        });
    } catch (err) {
        console.error("Mail send error:", err);
        return NextResponse.json({success: false, error: "Mailversand fehlgeschlagen."}, {status: 500});
    }
}
