import { prisma } from "@pmap/database";
import { getParticipantQrEmailTemplate, participantQrTemplateCodeValue } from "./_email-template";
import { participantName } from "./_qr";

type ParticipantEmailTarget = {
  registrationReference: string;
  firstName: string;
  middleName: string | null;
  lastName: string;
  company: string | null;
  participantCategory: string;
  user: { email: string };
};

type SendParticipantQrEmailOptions = {
  participant: ParticipantEmailTarget;
  qrSvg: string;
};

function renderTemplate(value: string, participant: ParticipantEmailTarget) {
  const replacements: Record<string, string> = {
    participantName: participantName(participant),
    reference: participant.registrationReference,
    category: participant.participantCategory,
    company: participant.company ?? "",
    email: participant.user.email
  };

  return value.replace(/\{\{(participantName|reference|category|company|email)\}\}/g, (_, key: string) => replacements[key] ?? "");
}

export async function sendParticipantQrEmail({ participant, qrSvg }: SendParticipantQrEmailOptions) {
  const template = await getParticipantQrEmailTemplate();
  const notificationTemplate = await prisma.notificationTemplate.upsert({
    where: { code: participantQrTemplateCodeValue() },
    update: {
      channel: "EMAIL",
      subject: template.subject,
      body: template.body,
      active: true
    },
    create: {
      code: participantQrTemplateCodeValue(),
      channel: "EMAIL",
      subject: template.subject,
      body: template.body,
      active: true
    }
  });

  const subject = renderTemplate(template.subject, participant);
  const body = renderTemplate(template.body, participant);
  const hasSmtpConfig = Boolean(process.env.SMTP_HOST && process.env.SMTP_FROM_EMAIL);

  await prisma.notificationLog.create({
    data: {
      templateId: notificationTemplate.id,
      channel: "EMAIL",
      recipient: participant.user.email,
      status: hasSmtpConfig ? "QUEUED" : "LOGGED",
      providerRef: hasSmtpConfig ? null : `local-qr-${participant.registrationReference}`,
      failureReason: hasSmtpConfig ? null : "SMTP is not configured. Email content and QR attachment were logged locally.",
      sentAt: hasSmtpConfig ? null : new Date()
    }
  });

  console.info("Participant QR email prepared", {
    to: participant.user.email,
    subject,
    body,
    attachmentName: `${participant.registrationReference}-qr.svg`,
    qrBytes: qrSvg.length,
    delivery: hasSmtpConfig ? "queued" : "logged"
  });
}

