import nodemailer from "nodemailer";
import type { PrismaClient, SmtpConfiguration, TpSmtpConfiguration } from "@prisma/client";
import { env } from "../env.js";

export type SmtpConfigInput = {
  senderName: string;
  senderEmail: string;
  smtpHost: string;
  smtpPort: string;
  smtpUser: string;
  smtpPassword: string;
  smtpType: "default" | "tls" | "ssl";
  status: "1" | "0";
};

export async function getActiveSmtp(prisma: PrismaClient): Promise<SmtpConfiguration | null> {
  return prisma.smtpConfiguration.findFirst({
    where: { status: "1" },
    orderBy: { id: "desc" },
  });
}

export async function getActiveTpSmtp(
  prisma: PrismaClient,
  projectId: bigint,
  trainingProviderId: bigint
): Promise<TpSmtpConfiguration | null> {
  return prisma.tpSmtpConfiguration.findFirst({
    where: { projectId, trainingProviderId, status: "1" },
    orderBy: { id: "desc" },
  });
}

async function getSystemSmtpConfig(prisma: PrismaClient) {
  const setting = await prisma.appSetting.findFirst({
    where: { key: "smtp_config" },
    select: { value: true },
  });
  return setting?.value as any;
}

async function getSystemSmtpTransport(prisma: PrismaClient) {
  const config = await getSystemSmtpConfig(prisma);
  if (!config) return null;
  
  return createTransportFromConfig({
    smtpHost: config.smtpHost,
    smtpPort: String(config.smtpPort),
    smtpUser: config.smtpUser,
    smtpPassword: config.smtpPassword,
    smtpType: config.smtpType || "starttls",
  });
}

type SmtpLikeConfig = Pick<SmtpConfiguration, "smtpHost" | "smtpPort" | "smtpType" | "smtpUser" | "smtpPassword">;

type EmailLayoutInput = {
  preheader?: string;
  title: string;
  intro: string;
  blocks?: Array<{ label: string; value: string }>;
  ctaLabel?: string;
  ctaUrl?: string;
  note?: string;
  outro?: string;
};

type RenderedEmail = { text: string; html: string };

const EMAIL_THEME = {
  surface: "#f8f9fa",
  card: "#ffffff",
  border: "#dbe2ea",
  header: "#003f87",
  headerAlt: "#0056b3",
  text: "#1f2937",
  mutedText: "#64748b",
  cta: "#003f87",
  ctaText: "#ffffff",
};

function appPortalUrl(): string {
  return env.FRONTEND_APP_URL ?? env.frontendOrigins[0] ?? env.PUBLIC_BASE_URL ?? "http://localhost:8080";
}

function safeUrl(raw: string): string {
  return encodeURI(raw.trim());
}

function logoHeaderHtml(): string {
  if (!env.EMAIL_LOGO_URL) return "";
  return `<div style="margin:0 0 10px;"><img src="${escapeHtml(safeUrl(env.EMAIL_LOGO_URL))}" alt="PBPS MIS" style="max-height:44px;width:auto;display:block;" /></div>`;
}

function renderEmailLayout(input: EmailLayoutInput): RenderedEmail {
  const blocks = input.blocks ?? [];
  const devLine =
    env.DEVELOPER_NAME && (env.DEVELOPER_URL || env.DEVELOPER_EMAIL)
      ? `Developer ${env.DEVELOPER_NAME} · ${env.DEVELOPER_URL ?? `mailto:${env.DEVELOPER_EMAIL}`}`
      : null;
  const textLines = [
    input.title,
    "",
    input.intro,
    ...(blocks.length
      ? ["", ...blocks.map((b) => `${b.label}: ${b.value}`)]
      : []),
    ...(input.ctaLabel && input.ctaUrl
      ? ["", `${input.ctaLabel}: ${input.ctaUrl}`]
      : []),
    ...(input.note ? ["", `Note: ${input.note}`] : []),
    ...(input.outro ? ["", input.outro] : []),
    ...(devLine ? ["", devLine] : []),
    "",
    "PBPS Monitoring and Verification Information System",
    "This is an automated message. Please do not reply to this email.",
  ];
  const text = textLines.join("\n");
  const blocksHtml = blocks.length
    ? `
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:16px 0;border-collapse:collapse;">
        ${blocks
          .map(
            (b) => `
          <tr>
            <td style="padding:8px 10px;border:1px solid ${EMAIL_THEME.border};background:${EMAIL_THEME.surface};font-size:12px;color:${EMAIL_THEME.mutedText};width:38%;">${escapeHtml(b.label)}</td>
            <td style="padding:8px 10px;border:1px solid ${EMAIL_THEME.border};background:${EMAIL_THEME.card};font-size:13px;color:${EMAIL_THEME.text};">${escapeHtml(b.value)}</td>
          </tr>`,
          )
          .join("")}
      </table>`
    : "";
  const ctaHtml =
    input.ctaLabel && input.ctaUrl
      ? `<p style="margin:18px 0 10px;"><a href="${escapeHtml(safeUrl(input.ctaUrl))}" style="display:inline-block;background:${EMAIL_THEME.cta};color:${EMAIL_THEME.ctaText};text-decoration:none;padding:10px 14px;border-radius:6px;font-size:13px;font-weight:600;">${escapeHtml(input.ctaLabel)}</a></p>`
      : "";
  const noteHtml = input.note
    ? `<p style="margin:12px 0 0;font-size:12px;color:${EMAIL_THEME.mutedText};"><strong>Note:</strong> ${escapeWithLineBreaks(input.note)}</p>`
    : "";
  const outroHtml = input.outro
    ? `<p style="margin:12px 0 0;font-size:13px;color:${EMAIL_THEME.text};">${escapeHtml(input.outro)}</p>`
    : "";
  const devHtml =
    devLine && env.DEVELOPER_NAME
      ? `<p style="margin:12px 0 0;font-size:11px;color:${EMAIL_THEME.mutedText};">
          Developer ${
            env.DEVELOPER_URL
              ? `<a href="${escapeHtml(safeUrl(env.DEVELOPER_URL))}" style="color:${EMAIL_THEME.headerAlt};text-decoration:none;">${escapeHtml(env.DEVELOPER_NAME)}</a>`
              : escapeHtml(env.DEVELOPER_NAME)
          }${
            env.DEVELOPER_EMAIL
              ? ` · <a href="mailto:${escapeHtml(env.DEVELOPER_EMAIL)}" style="color:${EMAIL_THEME.headerAlt};text-decoration:none;">${escapeHtml(env.DEVELOPER_EMAIL)}</a>`
              : ""
          }
        </p>`
      : "";
  const html = `
<!doctype html>
<html>
  <body style="margin:0;padding:0;background:${EMAIL_THEME.surface};font-family:Arial,Helvetica,sans-serif;">
    <div style="display:none;max-height:0;overflow:hidden;opacity:0;color:transparent;">${escapeHtml(input.preheader ?? input.title)}</div>
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:${EMAIL_THEME.surface};padding:24px 0;">
      <tr>
        <td align="center">
          <table role="presentation" width="600" cellpadding="0" cellspacing="0" style="width:600px;max-width:600px;background:${EMAIL_THEME.card};border:1px solid ${EMAIL_THEME.border};border-radius:10px;overflow:hidden;">
            <tr>
              <td style="padding:18px 22px;background:linear-gradient(135deg, ${EMAIL_THEME.header}, ${EMAIL_THEME.headerAlt});color:#ffffff;">
                <div style="font-size:13px;letter-spacing:0.2px;font-weight:700;">PBPS Monitoring and Verification Information System</div>
                <div style="font-size:11px;opacity:0.8;margin-top:2px;">Official system communication</div>
              </td>
            </tr>
            <tr>
              <td style="padding:22px;">
                ${logoHeaderHtml()}
                <h2 style="margin:0 0 10px;color:${EMAIL_THEME.header};font-size:20px;line-height:1.3;">${escapeHtml(input.title)}</h2>
                <p style="margin:0 0 10px;color:${EMAIL_THEME.text};font-size:14px;line-height:1.6;">${escapeHtml(input.intro)}</p>
                ${blocksHtml}
                ${ctaHtml}
                ${noteHtml}
                ${outroHtml}
                ${devHtml}
              </td>
            </tr>
            <tr>
              <td style="padding:14px 22px;background:${EMAIL_THEME.surface};border-top:1px solid ${EMAIL_THEME.border};color:${EMAIL_THEME.mutedText};font-size:11px;line-height:1.5;">
                This is an automated message from PBPS MIS. Please do not reply directly to this email.<br/>
                Portal: <a href="${escapeHtml(safeUrl(appPortalUrl()))}" style="color:${EMAIL_THEME.headerAlt};text-decoration:none;">${escapeHtml(appPortalUrl())}</a>
              </td>
            </tr>
          </table>
        </td>
      </tr>
    </table>
  </body>
</html>`;
  return { text, html };
}

export function createTransportFromConfig(c: SmtpLikeConfig) {
  const portNum = Number(c.smtpPort);
  const port = Number.isFinite(portNum) ? portNum : 587;

  // Laravel stores: default | tls | ssl
  // NodeMailer semantics:
  // - secure=true  => implicit TLS (usually 465)
  // - secure=false + requireTLS=true => STARTTLS (usually 587)
  // Be tolerant of legacy data where smtp_type=tls is used with port 465.
  // Also support "starttls" as an alias for "tls"
  const normalizedType = c.smtpType.toLowerCase();
  const wantsSsl = normalizedType === "ssl";
  const wantsTls = normalizedType === "tls" || normalizedType === "starttls";
  const isImplicitTlsPort = port === 465;

  const secure = wantsSsl || (wantsTls && isImplicitTlsPort);
  const requireTLS = wantsTls && !secure;

  return nodemailer.createTransport({
    host: c.smtpHost,
    port,
    secure,
    auth: { user: c.smtpUser, pass: c.smtpPassword },
    ...(requireTLS ? { requireTLS: true } : {}),
  });
}

export async function sendTestEmail(prisma: PrismaClient, to: string, subject: string, body: string) {
  const active = await getActiveSmtp(prisma);
  if (!active) {
    throw new Error("No active SMTP configuration. Set one as active first.");
  }

  const rendered = renderEmailLayout({
    preheader: "SMTP test message",
    title: subject,
    intro: "This is a test message from PBPS MIS SMTP settings.",
    blocks: [{ label: "Recipient", value: to }],
    note: body,
  });
  const transport = createTransportFromConfig(active);
  await transport.sendMail({
    from: `"${active.senderName}" <${active.senderEmail}>`,
    to,
    subject,
    text: rendered.text,
    html: rendered.html,
  });
}

export async function sendTwoFactorEmail(prisma: PrismaClient, to: string, code: string, minutesValid: number) {
  const active = await getActiveSmtp(prisma);
  if (!active) {
    throw new Error("No active SMTP configuration. Ask an admin to configure SMTP.");
  }

  const subject = `${active.senderName} — login verification code`;
  const rendered = renderEmailLayout({
    preheader: "Login verification code",
    title: "Your login verification code",
    intro: "Use the code below to complete sign-in to the PBPS MIS platform.",
    blocks: [
      { label: "Verification code", value: code },
      { label: "Expires in", value: `${minutesValid} minutes` },
    ],
    note: "Do not share this code with anyone. If you did not attempt to sign in, ignore this message and contact support.",
  });

  const transport = createTransportFromConfig(active);
  await transport.sendMail({
    from: `"${active.senderName}" <${active.senderEmail}>`,
    to,
    subject,
    text: rendered.text,
    html: rendered.html,
  });
}

export async function sendProviderWelcomeEmail(
  prisma: PrismaClient,
  to: string,
  providerName: string,
  temporaryPassword: string
) {
  const active = await getActiveSmtp(prisma);
  if (!active) {
    throw new Error("No active SMTP configuration. Ask an admin to configure SMTP.");
  }

  const subject = `${active.senderName} — provider account created`;
  const rendered = renderEmailLayout({
    preheader: "Provider account created",
    title: "Your Training Provider account is ready",
    intro: "Your account has been created in PBPS MIS. Use the credentials below to sign in.",
    blocks: [
      { label: "Provider", value: providerName },
      { label: "Username", value: to },
      { label: "Temporary password", value: temporaryPassword },
    ],
    ctaLabel: "Open PBPS MIS",
    ctaUrl: appPortalUrl(),
    note: "You will be prompted to change your password after first login.",
    outro: "Please keep credentials confidential.",
  });

  if (env.MAIL_MODE === "log") {
    console.log("[mail:log] sendProviderWelcomeEmail", { to, subject, text: rendered.text });
    return { mode: "log" as const, sent: false as const };
  }
  const transport = createTransportFromConfig(active);
  const info = await transport.sendMail({
    from: `"${active.senderName}" <${active.senderEmail}>`,
    to,
    subject,
    text: rendered.text,
    html: rendered.html,
  });
  if (Array.isArray(info.rejected) && info.rejected.length > 0) {
    throw new Error(`SMTP rejected recipient(s): ${info.rejected.join(", ")}`);
  }
  if (!Array.isArray(info.accepted) || info.accepted.length === 0) {
    throw new Error("SMTP did not accept any recipients.");
  }
  return { mode: "smtp" as const, sent: true as const, messageId: info.messageId, accepted: info.accepted };
}

export async function sendTpStaffWelcomeEmail(
  prisma: PrismaClient,
  to: string,
  staffName: string,
  providerName: string,
  roleLabel: string,
  scopeSummary: string[],
  temporaryPassword: string,
) {
  const active = await getActiveSmtp(prisma);
  if (!active) {
    throw new Error("No active SMTP configuration. Ask an admin to configure SMTP.");
  }

  const subject = `${active.senderName} — staff account created`;
  const rendered = renderEmailLayout({
    preheader: "Staff account created",
    title: "Your Training Provider staff account is ready",
    intro: `You have been invited as staff for ${providerName} in PBPS MIS.`,
    blocks: [
      { label: "Provider", value: providerName },
      { label: "Name", value: staffName },
      { label: "Role", value: roleLabel },
      { label: "Assigned access", value: scopeSummary.join("; ") || "—" },
      { label: "Username", value: to },
      { label: "Temporary password", value: temporaryPassword },
    ],
    ctaLabel: "Open PBPS MIS",
    ctaUrl: appPortalUrl(),
    note: "You will be prompted to change your password after first login.",
    outro: "Please keep credentials confidential.",
  });

  if (env.MAIL_MODE === "log") {
    console.log("[mail:log] sendTpStaffWelcomeEmail", { to, subject, text: rendered.text });
    return { mode: "log" as const, sent: false as const };
  }
  const transport = createTransportFromConfig(active);
  const info = await transport.sendMail({
    from: `"${active.senderName}" <${active.senderEmail}>`,
    to,
    subject,
    text: rendered.text,
    html: rendered.html,
  });
  if (Array.isArray(info.rejected) && info.rejected.length > 0) {
    throw new Error(`SMTP rejected recipient(s): ${info.rejected.join(", ")}`);
  }
  if (!Array.isArray(info.accepted) || info.accepted.length === 0) {
    throw new Error("SMTP did not accept any recipients.");
  }
  return { mode: "smtp" as const, sent: true as const, messageId: info.messageId, accepted: info.accepted };
}

export async function sendUserWelcomeEmail(
  prisma: PrismaClient,
  to: string,
  userName: string,
  temporaryPassword: string
) {
  const active = await getActiveSmtp(prisma);
  if (!active) {
    throw new Error("No active SMTP configuration. Ask an admin to configure SMTP.");
  }

  const subject = `${active.senderName} — user account created`;
  const rendered = renderEmailLayout({
    preheader: "User account created",
    title: "Your PBPS MIS account is ready",
    intro: "An administrator created your account in PBPS MIS. Use the credentials below to sign in.",
    blocks: [
      { label: "Name", value: userName },
      { label: "Username", value: to },
      { label: "Temporary password", value: temporaryPassword },
    ],
    ctaLabel: "Open PBPS MIS",
    ctaUrl: appPortalUrl(),
    note: "You will be prompted to change your password after first login.",
    outro: "Please keep credentials confidential.",
  });

  if (env.MAIL_MODE === "log") {
    console.log("[mail:log] sendUserWelcomeEmail", { to, subject, text: rendered.text });
    return { mode: "log" as const, sent: false as const };
  }
  const transport = createTransportFromConfig(active);
  const info = await transport.sendMail({
    from: `"${active.senderName}" <${active.senderEmail}>`,
    to,
    subject,
    text: rendered.text,
    html: rendered.html,
  });
  if (Array.isArray(info.rejected) && info.rejected.length > 0) {
    throw new Error(`SMTP rejected recipient(s): ${info.rejected.join(", ")}`);
  }
  if (!Array.isArray(info.accepted) || info.accepted.length === 0) {
    throw new Error("SMTP did not accept any recipients.");
  }
  return { mode: "smtp" as const, sent: true as const, messageId: info.messageId, accepted: info.accepted };
}

export function buildPasswordResetUrl(token: string): string {
  const base = appPortalUrl().replace(/\/$/, "");
  return `${base}/reset-password?token=${encodeURIComponent(token)}`;
}

/** Resend welcome email with username + password reset link (no raw password). */
export async function sendUserWelcomeResendEmail(
  prisma: PrismaClient,
  to: string,
  userName: string,
  passwordResetUrl: string,
) {
  const active = await getActiveSmtp(prisma);
  if (!active) {
    throw new Error("No active SMTP configuration. Ask an admin to configure SMTP.");
  }

  const subject = `${active.senderName} — PBPS MIS login details`;
  const rendered = renderEmailLayout({
    preheader: "Your PBPS MIS login details",
    title: "Your PBPS MIS account access",
    intro: "An administrator resent your PBPS MIS welcome email. Use the username below and the secure link to set your password.",
    blocks: [
      { label: "Name", value: userName },
      { label: "Username", value: to },
    ],
    ctaLabel: "Set your password",
    ctaUrl: passwordResetUrl,
    note: "This link expires after a limited time. If it has expired, contact your administrator to resend welcome email.",
    outro: "Please keep your login details confidential.",
  });

  if (env.MAIL_MODE === "log") {
    console.log("[mail:log] sendUserWelcomeResendEmail", { to, subject, text: rendered.text });
    return { mode: "log" as const, sent: false as const };
  }
  const transport = createTransportFromConfig(active);
  const info = await transport.sendMail({
    from: `"${active.senderName}" <${active.senderEmail}>`,
    to,
    subject,
    text: rendered.text,
    html: rendered.html,
  });
  if (Array.isArray(info.rejected) && info.rejected.length > 0) {
    throw new Error(`SMTP rejected recipient(s): ${info.rejected.join(", ")}`);
  }
  if (!Array.isArray(info.accepted) || info.accepted.length === 0) {
    throw new Error("SMTP did not accept any recipients.");
  }
  return { mode: "smtp" as const, sent: true as const, messageId: info.messageId, accepted: info.accepted };
}

export async function sendFeedbackResponseEmailWithTpSmtp(
  prisma: PrismaClient,
  projectId: bigint,
  trainingProviderId: bigint,
  to: string,
  subject: string,
  body: string,
  useSystemFallback: boolean = false
) {
  let tpSmtp = await getActiveTpSmtp(prisma, projectId, trainingProviderId);
  
  // If no TP SMTP configured
  if (!tpSmtp) {
    // If system fallback is NOT requested, throw error to show modal
    if (!useSystemFallback) {
      const error = new Error("NO_TP_SMTP_CONFIGURED");
      (error as any).code = "NO_TP_SMTP_CONFIGURED";
      throw error;
    }
    
    // System fallback IS requested - use system SMTP (same as welcome emails)
    const systemSmtp = await getActiveSmtp(prisma);
    if (!systemSmtp) {
      // No system SMTP configured
      const error = new Error("NO_SMTP_CONFIGURED");
      (error as any).code = "NO_SMTP_CONFIGURED";
      throw error;
    }
    
    // Use system SMTP to send email
    const rendered = renderEmailLayout({
      preheader: "Feedback response",
      title: subject,
      intro: "A response has been issued regarding your submitted feedback/grievance.",
      note: body,
    });
    const transport = createTransportFromConfig(systemSmtp);
    await transport.sendMail({
      from: `"${systemSmtp.senderName}" <${systemSmtp.senderEmail}>`,
      to,
      subject,
      text: rendered.text,
      html: rendered.html,
    });
    return; // Done - exit early
  }

  // Use TP SMTP
  const rendered = renderEmailLayout({
    preheader: "Feedback response",
    title: subject,
    intro: "A response has been issued regarding your submitted feedback/grievance.",
    note: body,
  });
  const transport = createTransportFromConfig(tpSmtp);
  await transport.sendMail({
    from: `"${tpSmtp.senderName}" <${tpSmtp.senderEmail}>`,
    to,
    subject,
    text: rendered.text,
    html: rendered.html,
  });
}

export function buildAlertEmailContent(args: {
  title: string;
  message: string;
  alertType: string;
  severity: string;
}): RenderedEmail {
  return renderEmailLayout({
    preheader: "PBPS alert notification",
    title: args.title,
    intro: args.message,
    blocks: [
      { label: "Alert type", value: args.alertType },
      { label: "Severity", value: args.severity },
    ],
    ctaLabel: "Open PBPS MIS",
    ctaUrl: appPortalUrl(),
  });
}

export function buildAdminDigestEmailContent(args: {
  digestDate: string;
  openAlertsCount: number;
  lines: string[];
}): RenderedEmail {
  return renderEmailLayout({
    preheader: `Daily digest ${args.digestDate}`,
    title: `PBPS Daily Alert Digest (${args.digestDate})`,
    intro: "Summary of currently open alerts for administrative follow-up.",
    blocks: [{ label: "Open alerts", value: String(args.openAlertsCount) }],
    note: args.lines.length ? args.lines.join("\n") : "No open alerts.",
    ctaLabel: "Review alerts in PBPS MIS",
    ctaUrl: appPortalUrl(),
  });
}

export function buildGenericNoticeEmailContent(args: { subject: string; message: string }): RenderedEmail {
  return renderEmailLayout({
    preheader: "PBPS system message",
    title: args.subject,
    intro: "Automated message from PBPS MIS.",
    note: args.message,
    ctaLabel: "Open PBPS MIS",
    ctaUrl: appPortalUrl(),
  });
}

export async function sendPublicFeedbackAcknowledgement(
  prisma: PrismaClient,
  args: {
    to: string;
    submitterName: string;
    category: "complaint" | "suggestion" | "question" | "appreciation";
    referenceCode: string;
    providerName: string;
    subject: string;
    dueAt: Date;
  }
): Promise<void> {
  const active = await getActiveSmtp(prisma);
  if (!active) return;

  const isAppreciationStyle = args.category === "appreciation" || args.category === "suggestion";
  const categoryLabel =
    args.category === "complaint"
      ? "Complaint"
      : args.category === "question"
        ? "Question"
        : args.category === "suggestion"
          ? "Suggestion"
          : "Appreciation";

  const rendered = renderEmailLayout({
    preheader: "Feedback submission received",
    title: isAppreciationStyle ? "Thank you for your feedback" : "We have received your feedback",
    intro: isAppreciationStyle
      ? `Dear ${args.submitterName}, thank you for sharing your ${categoryLabel.toLowerCase()}. Your input helps us improve services and delivery outcomes.`
      : `Dear ${args.submitterName}, thank you for contacting us. Your ${categoryLabel.toLowerCase()} has been registered and is under review by the responsible team.`,
    blocks: [
      { label: "Reference number", value: args.referenceCode },
      { label: "Category", value: categoryLabel },
      { label: "Training Provider", value: args.providerName },
      { label: "Subject", value: args.subject },
      { label: "Expected response by", value: args.dueAt.toISOString().slice(0, 10) },
    ],
    note: isAppreciationStyle
      ? "No further action is required from your side. We appreciate your engagement."
      : "Please keep this reference number for follow-up. If needed, our team may contact you for clarification.",
    ctaLabel: "Open PBPS MIS",
    ctaUrl: appPortalUrl(),
    outro: "Best regards,\nPBPS Monitoring and Verification Team",
  });

  const transport = createTransportFromConfig(active);
  const subject = isAppreciationStyle
    ? `Thank you for your feedback (${args.referenceCode})`
    : `Feedback received (${args.referenceCode})`;
  await transport.sendMail({
    from: `"${active.senderName}" <${active.senderEmail}>`,
    to: args.to,
    subject,
    text: rendered.text,
    html: rendered.html,
  });
}

export async function sendFeedbackResolvedNotificationWithTpSmtp(
  prisma: PrismaClient,
  args: {
    projectId: bigint;
    trainingProviderId: bigint;
    to: string;
    submitterName: string;
    referenceCode: string;
    category: "complaint" | "suggestion" | "question" | "appreciation";
    subject: string;
    resolvedAt: Date;
  }
): Promise<void> {
  const active = await getActiveTpSmtp(prisma, args.projectId, args.trainingProviderId);
  if (!active) return;

  const categoryLabel =
    args.category === "complaint"
      ? "Complaint"
      : args.category === "question"
        ? "Question"
        : args.category === "suggestion"
          ? "Suggestion"
          : "Appreciation";
  const rendered = renderEmailLayout({
    preheader: "Feedback case resolved",
    title: "Your feedback case has been resolved",
    intro: `Dear ${args.submitterName}, thank you for your patience. Your submitted feedback has been marked as resolved.`,
    blocks: [
      { label: "Reference number", value: args.referenceCode },
      { label: "Category", value: categoryLabel },
      { label: "Subject", value: args.subject },
      { label: "Resolved on", value: args.resolvedAt.toISOString().slice(0, 10) },
    ],
    note: "If you still need support on this matter, you may submit a new feedback item referencing this case number.",
    ctaLabel: "Open PBPS MIS",
    ctaUrl: appPortalUrl(),
    outro: "Best regards,\nPBPS Monitoring and Verification Team",
  });

  const transport = createTransportFromConfig(active);
  await transport.sendMail({
    from: `"${active.senderName}" <${active.senderEmail}>`,
    to: args.to,
    subject: `Feedback resolved (${args.referenceCode})`,
    text: rendered.text,
    html: rendered.html,
  });
}

function escapeHtml(input: string): string {
  return input
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll("\"", "&quot;")
    .replaceAll("'", "&#039;");
}

function escapeWithLineBreaks(input: string): string {
  return escapeHtml(input).replaceAll("\n", "<br/>");
}


export async function sendNewFeedbackNotificationToProvider(
  prisma: PrismaClient,
  args: {
    projectId: bigint;
    trainingProviderId: bigint;
    referenceCode: string;
    category: string;
    subject: string;
    submitterName: string;
    submittedAt: Date;
    dueAt: Date;
  }
) {
  // Get TP users who should receive notifications
  const tpUsers = await prisma.user.findMany({
    where: {
      tpStaffMemberships: {
        some: {
          projectId: args.projectId,
          trainingProviderId: args.trainingProviderId,
          isActive: true,
        },
      },
    },
    select: { email: true, name: true },
  });

  if (tpUsers.length === 0) {
    console.log(`[feedback] No TP users found for provider ${args.trainingProviderId}`);
    return;
  }

  // Use system SMTP to send notifications to providers
  const transport = await getSystemSmtpTransport(prisma);
  if (!transport) {
    console.log(`[feedback] No system SMTP configured, skipping notification`);
    return;
  }

  const categoryLabel = args.category.charAt(0).toUpperCase() + args.category.slice(1);
  const daysRemaining = Math.ceil((args.dueAt.getTime() - args.submittedAt.getTime()) / (1000 * 60 * 60 * 24));

  const rendered = renderEmailLayout({
    preheader: "New feedback submission requires your attention",
    title: `New ${categoryLabel}: ${args.subject}`,
    intro: `A new feedback has been submitted and assigned to your training provider. Please review and respond within ${daysRemaining} days.`,
    blocks: [
      { label: "Reference Code", value: args.referenceCode },
      { label: "Category", value: categoryLabel },
      { label: "Subject", value: args.subject },
      { label: "Submitted At", value: args.submittedAt.toISOString().slice(0, 16).replace("T", " ") },
      { label: "Due Date", value: args.dueAt.toISOString().slice(0, 16).replace("T", " ") },
      { label: "Days to Respond", value: `${daysRemaining} days` },
    ],
    ctaLabel: "View & Respond to Feedback",
    ctaUrl: appPortalUrl(),
    note: "Please log in to the PBPS MIS system to view the full details and respond to this feedback. Submitter contact details are confidential and not included in this notification.",
  });

  const recipients = tpUsers.map((u) => u.email).join(", ");
  const systemSmtpConfig = await getSystemSmtpConfig(prisma);

  await transport.sendMail({
    from: `"${systemSmtpConfig?.senderName || 'PBPS MIS'}" <${systemSmtpConfig?.senderEmail || 'noreply@pbps.gov'}>`,
    to: recipients,
    subject: `New Feedback: ${args.referenceCode} - ${args.subject}`,
    text: rendered.text,
    html: rendered.html,
  });

  console.log(`[feedback] Notified ${tpUsers.length} TP user(s) about new feedback ${args.referenceCode}`);
}

export async function sendFeedbackDueDateReminderToProvider(
  prisma: PrismaClient,
  args: {
    projectId: bigint;
    trainingProviderId: bigint;
    feedbackId: bigint;
    referenceCode: string;
    category: string;
    subject: string;
    submitterName: string;
    submittedAt: Date;
    dueAt: Date;
  }
) {
  // Get TP users who should receive notifications
  const tpUsers = await prisma.user.findMany({
    where: {
      tpStaffMemberships: {
        some: {
          projectId: args.projectId,
          trainingProviderId: args.trainingProviderId,
          isActive: true,
        },
      },
    },
    select: { email: true, name: true },
  });

  if (tpUsers.length === 0) {
    console.log(`[feedback-reminder] No TP users found for provider ${args.trainingProviderId}`);
    return;
  }

  // Use system SMTP to send notifications to providers
  const transport = await getSystemSmtpTransport(prisma);
  if (!transport) {
    console.log(`[feedback-reminder] No system SMTP configured, skipping reminder`);
    return;
  }

  const now = new Date();
  const hoursRemaining = Math.max(0, Math.ceil((args.dueAt.getTime() - now.getTime()) / (1000 * 60 * 60)));
  const daysRemaining = Math.max(0, Math.ceil(hoursRemaining / 24));

  const categoryLabel = args.category.charAt(0).toUpperCase() + args.category.slice(1);
  
  const title = `⏰ Reminder: ${args.referenceCode} - Response Due in ${daysRemaining} Day(s)`;
  const intro = `This feedback requires your response within ${daysRemaining} day(s). Please review and respond as soon as possible to meet the 7-day service level agreement.`;

  const rendered = renderEmailLayout({
    preheader: "Feedback response due soon",
    title,
    intro,
    blocks: [
      { label: "Reference Code", value: args.referenceCode },
      { label: "Category", value: categoryLabel },
      { label: "Subject", value: args.subject },
      { label: "Submitted At", value: args.submittedAt.toISOString().slice(0, 16).replace("T", " ") },
      { label: "Due Date", value: args.dueAt.toISOString().slice(0, 16).replace("T", " ") },
      { 
        label: "Time Remaining", 
        value: `${daysRemaining} days (${hoursRemaining} hours)` 
      },
    ],
    ctaLabel: "View & Respond Now",
    ctaUrl: appPortalUrl(),
    note: "Please log in to the PBPS MIS system to respond to this feedback before the deadline. Submitter contact details are confidential and not included in this notification.",
  });

  const recipients = tpUsers.map((u) => u.email).join(", ");
  const systemSmtpConfig = await getSystemSmtpConfig(prisma);

  await transport.sendMail({
    from: `"${systemSmtpConfig?.senderName || 'PBPS MIS'}" <${systemSmtpConfig?.senderEmail || 'noreply@pbps.gov'}>`,
    to: recipients,
    subject: `⏰ Reminder: ${args.referenceCode} - Due in ${daysRemaining} day(s)`,
    text: rendered.text,
    html: rendered.html,
  });

  console.log(`[feedback-reminder] Sent reminder notification to ${tpUsers.length} TP user(s) for feedback ${args.referenceCode}`);
}
