import { prisma } from '@/lib/prisma';

type MailingListSource = 'CUSTOMER' | 'NEWSLETTER' | 'GUEST';

// Never touches `subscribed` or `source` on an existing row — so re-subscribing
// to the newsletter, or placing a second guest order, can't silently undo an
// admin's opt-out or overwrite how someone was first attributed.
export async function upsertMailingListEntry({
  email,
  name,
  source,
}: {
  email: string;
  name?: string | null;
  source: MailingListSource;
}) {
  const trimmed = email.trim().toLowerCase();
  if (!trimmed) return;

  await prisma.mailingListEntry.upsert({
    where: { email: trimmed },
    create: { email: trimmed, name: name || null, source },
    update: name ? { name } : {},
  });
}
