import { prisma } from "@/lib/prisma";
import { mailButton, mailShell, sendToolaroMail } from "@/lib/mail";
import { hashIp, randomToken, sha256 } from "@/lib/security";

export async function createNewsletterOptIn({
  email,
  userId,
  source,
  ip,
}: {
  email: string;
  userId?: string;
  source: string;
  ip?: string | null;
}) {
  const token = randomToken(32);
  const base = (process.env.NEXT_PUBLIC_SITE_URL ?? "https://toolaro.org").replace(/\/$/, "");
  await prisma.newsletterSubscription.create({
    data: {
      email,
      userId,
      source,
      status: "pending",
      tokenHash: sha256(token),
      requestedIpHash: hashIp(ip),
    },
  });

  const url = `${base}/api/newsletter/confirm?token=${encodeURIComponent(token)}`;
  await sendToolaroMail({
    to: email,
    subject: "Toolaro Newsletter – Bitte bestätigen",
    html: mailShell(
      "Fast geschafft!",
      `<p style="margin:0 0 16px;font-size:17px;font-weight:bold;color:#1a1a2e;">Nur noch ein Klick!</p>
       <p style="margin:0 0 14px;">Du hast dich für den Toolaro-Newsletter angemeldet. Bestätige jetzt deine Adresse, damit du keine News verpasst:</p>
       <ul style="margin:0 0 16px;padding-left:20px;color:#1a1a2e;line-height:2;">
         <li>Neue Tools als erstes entdecken</li>
         <li>Tipps &amp; Tricks zu unseren Webtools</li>
         <li>Premium-Angebote und Updates</li>
       </ul>
       ${mailButton("Newsletter bestätigen", url)}
       <p style="margin:20px 0 0;font-size:13px;color:#4a5568;">Falls du dich nicht angemeldet hast, kannst du diese E-Mail einfach ignorieren.</p>`,
      "Bitte bestätige deine Toolaro Newsletter-Anmeldung."
    ),
    text: `Bitte bestätige deine Newsletter-Anmeldung:\n${url}`,
  });
}

export async function setNewsletterStatus(userId: string, email: string, status: "active" | "unsubscribed") {
  await prisma.newsletterSubscription.create({
    data: {
      userId,
      email,
      source: "account",
      status,
      confirmedAt: status === "active" ? new Date() : null,
      unsubscribedAt: status === "unsubscribed" ? new Date() : null,
    },
  });
  await prisma.user.update({
    where: { id: userId },
    data: { newsletterOptIn: status === "active" },
  });
}
