import { Resend } from "resend";
import { db } from "@/lib/db";
import type { PurchaseOrder, User } from "@prisma/client";

const isDev = process.env.NODE_ENV === "development";
const resend = isDev ? null : new Resend(process.env.RESEND_API_KEY);
const FROM = `${process.env.EMAIL_FROM_NAME ?? "Pelagia Portal"} <${process.env.EMAIL_FROM ?? "noreply@pelagiaportal.com"}>`;

export type NotificationEvent =
  | "PO_SUBMITTED"
  | "PO_APPROVED"
  | "PO_APPROVED_WITH_NOTE"
  | "PO_REJECTED"
  | "EDITS_REQUESTED"
  | "VENDOR_ID_REQUESTED"
  | "VENDOR_ID_PROVIDED"
  | "PAYMENT_PROCESSING"
  | "PAYMENT_SENT"
  | "RECEIPT_CONFIRMED";

interface NotifyParams {
  event: NotificationEvent;
  po: PurchaseOrder & { submitter: User };
  recipients: User[];
  note?: string;
}

export async function notify({ event, po, recipients, note }: NotifyParams) {
  const subject = buildSubject(event, po.poNumber);
  if (!subject) return;

  await Promise.allSettled(
    recipients.map(async (recipient) => {
      let status = "sent";
      if (isDev) {
        console.log(
          `\n📧 [DEV EMAIL] To: ${recipient.email}\n   Subject: ${subject}\n   Body: ${buildBody(event, po, note)}\n`
        );
      } else {
        try {
          const { error } = await resend!.emails.send({
            from: FROM,
            to: recipient.email,
            subject,
            html: buildHtml(event, po, recipient, note),
          });
          if (error) status = "failed";
        } catch {
          status = "failed";
        }
      }
      await db.notification.create({
        data: { subject, body: subject, status, poId: po.id, userId: recipient.id },
      });
    })
  );
}

function buildSubject(event: NotificationEvent, poNumber: string): string | null {
  const base = `PO ${poNumber}`;
  const map: Record<NotificationEvent, string> = {
    PO_SUBMITTED: `${base} submitted for review`,
    PO_APPROVED: `${base} has been approved`,
    PO_APPROVED_WITH_NOTE: `${base} has been approved`,
    PO_REJECTED: `${base} has been rejected`,
    EDITS_REQUESTED: `Edits requested on ${base}`,
    VENDOR_ID_REQUESTED: `Vendor ID needed for ${base}`,
    VENDOR_ID_PROVIDED: `Vendor ID provided for ${base}`,
    PAYMENT_PROCESSING: `Payment initiated for ${base}`,
    PAYMENT_SENT: `Payment confirmed for ${base}`,
    RECEIPT_CONFIRMED: `Receipt confirmed — ${base} closed`,
  };
  return map[event] ?? null;
}

function buildHtml(
  event: NotificationEvent,
  po: PurchaseOrder & { submitter: User },
  recipient: User,
  note?: string
): string {
  return `
<!DOCTYPE html>
<html>
<body style="font-family:Inter,sans-serif;max-width:560px;margin:0 auto;padding:32px 24px;color:#111827;">
  <div style="border-bottom:2px solid #2563eb;padding-bottom:12px;margin-bottom:24px;">
    <span style="font-size:20px;font-weight:700;color:#1d4ed8;">Pelagia Portal</span>
  </div>
  <p style="margin:0 0 16px;">Hi ${recipient.name},</p>
  <p style="margin:0 0 24px;">${buildBody(event, po, note)}</p>
  <div style="background:#f3f4f6;border-radius:8px;padding:16px;font-size:13px;color:#374151;">
    <strong>PO Number:</strong> ${po.poNumber}<br/>
    <strong>Title:</strong> ${po.title}<br/>
    <strong>Submitted by:</strong> ${po.submitter.name}
  </div>
  <p style="margin-top:32px;font-size:12px;color:#9ca3af;">
    You received this message because you are a stakeholder on this purchase order.
  </p>
</body>
</html>`;
}

function buildBody(
  event: NotificationEvent,
  po: PurchaseOrder & { submitter: User },
  note?: string
): string {
  const noteHtml = note
    ? `<br/><br/><em style="color:#374151;">"${note}"</em>`
    : "";

  switch (event) {
    case "PO_SUBMITTED":
      return `<strong>${po.submitter.name}</strong> has submitted purchase order <strong>${po.poNumber}</strong> for your review.`;
    case "PO_APPROVED":
    case "PO_APPROVED_WITH_NOTE":
      return `Your purchase order <strong>${po.poNumber}</strong> has been <span style="color:#16a34a;font-weight:600;">approved</span>.${noteHtml}`;
    case "PO_REJECTED":
      return `Your purchase order <strong>${po.poNumber}</strong> has been <span style="color:#dc2626;font-weight:600;">rejected</span>.${noteHtml}`;
    case "EDITS_REQUESTED":
      return `Edits have been requested on <strong>${po.poNumber}</strong>. Please update the order and resubmit.${noteHtml}`;
    case "VENDOR_ID_REQUESTED":
      return `A vendor ID is required before <strong>${po.poNumber}</strong> can be approved. Please update the PO with the correct vendor details.`;
    case "VENDOR_ID_PROVIDED":
      return `The vendor ID has been provided for <strong>${po.poNumber}</strong>. It is ready for your review.`;
    case "PAYMENT_PROCESSING":
      return `Payment is being processed for <strong>${po.poNumber}</strong>.`;
    case "PAYMENT_SENT":
      return `Payment has been confirmed for <strong>${po.poNumber}</strong>. Please confirm delivery/receipt when the goods arrive.`;
    case "RECEIPT_CONFIRMED":
      return `Receipt has been confirmed for <strong>${po.poNumber}</strong>. The order is now closed.`;
    default:
      return `There has been an update on purchase order ${po.poNumber}.`;
  }
}
