import nodemailer from "nodemailer";
import { prisma } from "../config/prisma.js";

async function getSmtpConfig() {
  const settings = await prisma.setting.findMany({
    where: { key: { in: ["smtp_host", "smtp_port", "smtp_secure", "smtp_user", "smtp_pass", "smtp_from", "notify_email"] } },
  });
  const get = (k: string, d = "") => settings.find((s) => s.key === k)?.value ?? d;
  return {
    host: get("smtp_host"),
    port: Number(get("smtp_port", "587")),
    secure: get("smtp_secure", "false") === "true",
    user: get("smtp_user"),
    pass: get("smtp_pass"),
    from: get("smtp_from"),
    notifyEmail: get("notify_email"),
  };
}

export function buildAlertHtml(opts: {
  title: string;
  entityName: string;
  expiryDate: Date;
  daysRemaining: number;
  priorityLabel: string;
  priorityColor: string;
  companyName: string;
}) {
  const dateStr = new Date(opts.expiryDate).toLocaleDateString("ar-EG", { year: "numeric", month: "long", day: "numeric" });
  return `
  <div dir="rtl" style="font-family:'Segoe UI',Tahoma,Arial,sans-serif;background:#f4f5f7;padding:24px;">
    <div style="max-width:600px;margin:auto;background:#ffffff;border-radius:12px;overflow:hidden;border:1px solid #e5e7eb;">
      <div style="background:#1e3a8a;color:#ffffff;padding:20px 28px;text-align:center;">
        <h2 style="margin:0;font-size:20px;">تنبيه تجديد مستند</h2>
      </div>
      <div style="padding:28px;">
        <p style="font-size:15px;color:#374151;margin:0 0 16px;">تم إصدار تنبيه تلقائي بخصوص المستند التالي:</p>
        <table style="width:100%;border-collapse:collapse;font-size:14px;">
          <tr><td style="padding:8px 0;color:#6b7280;">المستند</td><td style="padding:8px 0;font-weight:600;color:#111827;">${opts.title}</td></tr>
          <tr><td style="padding:8px 0;color:#6b7280;">الجهة</td><td style="padding:8px 0;font-weight:600;color:#111827;">${opts.entityName} — ${opts.companyName}</td></tr>
          <tr><td style="padding:8px 0;color:#6b7280;">تاريخ الانتهاء</td><td style="padding:8px 0;font-weight:600;color:#111827;">${dateStr}</td></tr>
          <tr><td style="padding:8px 0;color:#6b7280;">الأيام المتبقية</td><td style="padding:8px 0;font-weight:600;color:#111827;">${opts.daysRemaining} يوم</td></tr>
          <tr>
            <td style="padding:8px 0;color:#6b7280;">الأولوية</td>
            <td style="padding:8px 0;"><span style="background:${opts.priorityColor};color:#fff;padding:4px 14px;border-radius:9999px;font-size:12px;font-weight:600;">${opts.priorityLabel}</span></td>
          </tr>
        </table>
        <p style="font-size:13px;color:#9ca3af;margin:24px 0 0;">هذه رسالة تلقائية من نظام إدارة العمالة والمستندات. يرجى متابعة التجديد قبل انتهاء المستند.</p>
      </div>
    </div>
  </div>`;
}

export async function sendEmail(to: string, subject: string, html: string) {
  const cfg = await getSmtpConfig();
  if (!cfg.host || !cfg.user) {
    throw new Error("SMTP غير مُهيأ");
  }
  const transporter = nodemailer.createTransport({
    host: cfg.host,
    port: cfg.port,
    secure: cfg.secure,
    auth: { user: cfg.user, pass: cfg.pass },
  });
  return transporter.sendMail({
    from: cfg.from || cfg.user,
    to,
    subject,
    html,
  });
}

export async function sendExpiryAlert(doc: {
  documentId: number | null;
  title: string;
  entityType: "company" | "employee";
  entityName: string;
  companyName: string;
  expiryDate: Date;
  daysRemaining: number;
  priorityLabel: string;
  priorityColor: string;
  to: string;
  eventKey?: string;
}) {
  const html = buildAlertHtml({
    title: doc.title,
    entityName: doc.entityName,
    expiryDate: doc.expiryDate,
    daysRemaining: doc.daysRemaining,
    priorityLabel: doc.priorityLabel,
    priorityColor: doc.priorityColor,
    companyName: doc.companyName,
  });
  try {
    await sendEmail(doc.to, `⚠️ تنبيه: ${doc.title} يقترب من الانتهاء`, html);
    await prisma.notification.create({
      data: {
        type: "email",
        documentId: doc.documentId ?? null,
        eventKey: doc.eventKey ?? null,
        entityType: doc.entityType,
        entityName: doc.entityName,
        subject: `تنبيه تجديد: ${doc.title}`,
        message: `المستند ينتهي خلال ${doc.daysRemaining} يوم`,
        toEmail: doc.to,
        isSuccess: true,
      },
    });
    return true;
  } catch (err) {
    await prisma.notification.create({
      data: {
        type: "email",
        documentId: doc.documentId ?? null,
        entityType: doc.entityType,
        entityName: doc.entityName,
        subject: `فشل إرسال تنبيه: ${doc.title}`,
        message: `فشل إرسال البريد: ${(err as Error).message}`,
        toEmail: doc.to,
        isSuccess: false,
      },
    });
    console.error("Email alert failed:", err);
    return false;
  }
}
