'use server';

import { redirect } from 'next/navigation';
import { prisma } from '@/lib/prisma';
import { sendCustomerBroadcast } from '@/lib/mail';

export async function updateSubscribed(formData: FormData) {
  const id = String(formData.get('id') ?? '');
  if (!id) return;

  const subscribed = String(formData.get('subscribed') ?? '') === '1';

  await prisma.mailingListEntry.update({ where: { id }, data: { subscribed } });
  redirect('/admin/customers');
}

export async function sendBulkEmail(formData: FormData) {
  const subject = String(formData.get('subject') ?? '').trim();
  const message = String(formData.get('message') ?? '').trim();
  if (!subject || !message) {
    throw new Error('Subject and message are required.');
  }

  const attachmentFile = formData.get('attachment') as File | null;
  const attachment =
    attachmentFile && attachmentFile.size > 0
      ? {
          filename: attachmentFile.name,
          content: Buffer.from(await attachmentFile.arrayBuffer()),
          contentType: attachmentFile.type || undefined,
        }
      : null;

  const recipients = await prisma.mailingListEntry.findMany({ where: { subscribed: true } });

  let sent = 0;
  let failed = 0;
  for (const recipient of recipients) {
    const result = await sendCustomerBroadcast({
      to: recipient.email,
      name: recipient.name,
      subject,
      message,
      attachment,
    });
    if (result.sent) sent += 1;
    else failed += 1;
  }

  redirect(`/admin/customers?sent=${sent}&failed=${failed}`);
}
