"use server";

import { contactFormSchema } from "./zod";
import { headers } from "next/headers";
import { z } from "zod";
import { createTransport } from "./mailer";

export async function sendContactMail(body: z.infer<typeof contactFormSchema>) {
  const escapeHtml = (s: string) => {
    return s
      .replaceAll("&", "&amp;")
      .replaceAll("<", "&lt;")
      .replaceAll(">", "&gt;")
      .replaceAll('"', "&quot;")
      .replaceAll("'", "&#039;");
  };
  const parsed = contactFormSchema.safeParse(body);
  if (!parsed.success) {
    return false;
  }
  const { hp, name, email, message, budget } = parsed.data;
  // detect spam
  if (hp && hp.trim().length > 0) {
    return false;
  }
  const transporter = createTransport();

  const h = await headers();
  const ip = h.get("x-forwarded-for")?.split(",")[0]?.trim() || "unknown";

  try {
    // Optional: Transport prüfen
    await transporter.verify();

    const from = process.env.SMTP_FROM!;
    const to = process.env.SMTP_TO!;

    const subject = `Neue Kontaktanfrage von ${name}`;
    const text = [
      `Name: ${name}`,
      `E-Mail: ${email}`,
      `IP: ${ip}`,
      ``,
      `Nachricht:`,
      message,
    ].join("\n");

    const html = `
      <div style="font-family:system-ui,-apple-system,Segoe UI,Roboto,Arial,sans-serif;line-height:1.5">
        <h2 style="margin:0 0 8px">Neue Kontaktanfrage</h2>
        <p><strong>Name:</strong> ${escapeHtml(name)}</p>
        <p><strong>E-Mail:</strong> ${escapeHtml(email)}</p>
        <p><strong>Budget:</strong> ${escapeHtml(budget)}</p>
        <p><strong>IP:</strong> ${escapeHtml(ip)}</p>
        <br />
        <h3>Message</h3>
        <hr style="border:none;border-top:1px solid #ddd;margin:12px 0"/>
        <p style="white-space:pre-wrap">${escapeHtml(message)}</p>
      </div>
    `;

    await transporter.sendMail({
      from, // MUSS zu deiner Domain passen (SPF/DMARC)
      to, // du selbst
      replyTo: email, // damit du direkt antworten kannst
      subject,
      text,
      html,
      envelope: {
        from, // technische Absenderadresse (Return-Path aligned)
        to,
      },
      headers: {
        "X-Contact-Form": "portfolio",
      },
    });

    return true;
  } catch (err) {
    console.log(err);

    return false;
  }
}
