import nodemailer from "nodemailer";

type InviteEmailInput = {
  to: string;
  inviteUrl: string;
  invitedBy: string;
};

type PasswordResetEmailInput = {
  to: string;
  resetUrl: string;
};

export function isEmailConfigured() {
  return Boolean(process.env.SMTP_HOST && process.env.SMTP_USER && process.env.SMTP_PASS);
}

function createTransporter() {
  return nodemailer.createTransport({
    host: process.env.SMTP_HOST,
    port: Number(process.env.SMTP_PORT ?? 587),
    secure: Number(process.env.SMTP_PORT ?? 587) === 465,
    auth: {
      user: process.env.SMTP_USER,
      pass: process.env.SMTP_PASS
    }
  });
}

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

function emailShell(input: { title: string; intro: string; buttonLabel: string; url: string; footer: string }) {
  const safeTitle = escapeHtml(input.title);
  const safeIntro = escapeHtml(input.intro);
  const safeButtonLabel = escapeHtml(input.buttonLabel);
  const safeUrl = escapeHtml(input.url);
  const safeFooter = escapeHtml(input.footer);
  return `
      <div style="margin:0;padding:32px;background:#f7f8ff;font-family:Inter,Segoe UI,Arial,sans-serif;color:#17211d">
        <div style="max-width:560px;margin:0 auto;background:#fff;border:1px solid #dfe4f3;border-radius:12px;padding:28px">
          <div style="height:48px;width:48px;border-radius:10px;background:linear-gradient(135deg,#1828e8,#5d20ff);color:#fff;display:flex;align-items:center;justify-content:center;font-weight:800;font-size:22px">I</div>
          <h1 style="margin:24px 0 8px;font-size:28px;line-height:1.1">${safeTitle}</h1>
          <p style="margin:0 0 22px;color:#475569;font-size:16px;line-height:1.5">${safeIntro}</p>
          <a href="${safeUrl}" style="display:inline-block;background:#1828e8;color:#fff;text-decoration:none;font-weight:800;border-radius:8px;padding:14px 18px">${safeButtonLabel}</a>
          <p style="margin:22px 0 0;color:#64748b;font-size:13px;line-height:1.5">${safeFooter}</p>
          <p style="word-break:break-all;color:#1119a8;font-size:13px">${safeUrl}</p>
        </div>
      </div>
    `;
}

export async function sendInviteEmail(input: InviteEmailInput) {
  if (!isEmailConfigured()) return { sent: false };

  const transporter = createTransporter();
  const intro = `${input.invitedBy} invited you to manage inventory across warehouses, trucks, parts, and assemblies.`;

  await transporter.sendMail({
    to: input.to,
    from: process.env.SMTP_FROM ?? "SSS Inventory <inventory@example.com>",
    subject: "You're invited to SSS Inventory",
    text: [
      `${input.invitedBy} invited you to SSS Inventory.`,
      "",
      "Open this secure invite link to create your password:",
      input.inviteUrl,
      "",
      "This invite expires in 14 days."
    ].join("\n"),
    html: emailShell({
      title: "You're invited to SSS Inventory",
      intro,
      buttonLabel: "Create your password",
      url: input.inviteUrl,
      footer: "This invite expires in 14 days. If the button does not work, paste this link into your browser:"
    })
  });

  return { sent: true };
}

export async function sendPasswordResetEmail(input: PasswordResetEmailInput) {
  if (!isEmailConfigured()) return { sent: false };

  const transporter = createTransporter();
  await transporter.sendMail({
    to: input.to,
    from: process.env.SMTP_FROM ?? "SSS Inventory <inventory@example.com>",
    subject: "Reset your SSS Inventory password",
    text: [
      "We received a request to reset the password for your SSS Inventory account.",
      "",
      "Open this secure link to choose a new password:",
      input.resetUrl,
      "",
      "This reset link expires in 1 hour. If you did not request this, you can ignore this email and your password will stay unchanged."
    ].join("\n"),
    html: emailShell({
      title: "Reset your SSS Inventory password",
      intro: "We received a request to reset the password for your SSS Inventory account. Use the secure button below to choose a new password.",
      buttonLabel: "Reset password",
      url: input.resetUrl,
      footer: "This reset link expires in 1 hour. If you did not request this, you can ignore this email and your password will stay unchanged. If the button does not work, paste this link into your browser:"
    })
  });

  return { sent: true };
}
