import * as nodemailer from "nodemailer";
import { getConfig } from "../config.js";

interface AuthEmail {
  to: string;
  subject: string;
  text: string;
  html: string;
}

function escapeHtml(value: string): string {
  return value
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}

export function assertAuthEmailConfigured(): void {
  const config = getConfig().authEmail;

  if (!config.smtpUser || !config.smtpPass) {
    throw new Error(
      `SMTP is not configured. Set SKOLA_SMTP_USER and SKOLA_SMTP_PASS for ${config.adminEmail}. For Gmail, use an app password, not the normal account password.`
    );
  }
}

async function sendAuthEmail(message: AuthEmail): Promise<void> {
  assertAuthEmailConfigured();
  const config = getConfig().authEmail;
  const transport = nodemailer.createTransport({
    host: config.smtpHost,
    port: config.smtpPort,
    secure: config.smtpSecure,
    auth: {
      user: config.smtpUser,
      pass: config.smtpPass
    }
  });

  await transport.sendMail({
    from: `Skola <${config.fromEmail}>`,
    to: message.to,
    subject: message.subject,
    text: message.text,
    html: message.html
  });
}

export async function sendVerificationEmail(params: {
  to: string;
  name: string;
  verificationUrl: string;
}): Promise<void> {
  const safeName = escapeHtml(params.name);
  const safeUrl = escapeHtml(params.verificationUrl);

  await sendAuthEmail({
    to: params.to,
    subject: "Verify your Skola account",
    text: `Hi ${params.name},\n\nVerify your Skola account by opening this link:\n${params.verificationUrl}\n\nIf you did not create this account, ignore this email.`,
    html: `
      <div style="font-family:Arial,sans-serif;line-height:1.5;color:#17332c">
        <h2>Verify your Skola account</h2>
        <p>Hi ${safeName},</p>
        <p>Confirm this email address to finish setting up your Skola account.</p>
        <p><a href="${safeUrl}" style="display:inline-block;padding:10px 16px;background:#c9623d;color:#fff;text-decoration:none;border-radius:999px">Verify email</a></p>
        <p>If the button does not work, paste this URL into your browser:</p>
        <p>${safeUrl}</p>
      </div>
    `
  });
}

export async function sendPasswordResetEmail(params: {
  to: string;
  name: string;
  resetUrl: string;
}): Promise<void> {
  const safeName = escapeHtml(params.name);
  const safeUrl = escapeHtml(params.resetUrl);

  await sendAuthEmail({
    to: params.to,
    subject: "Reset your Skola password",
    text: `Hi ${params.name},\n\nReset your Skola password by opening this link:\n${params.resetUrl}\n\nIf you did not request this reset, ignore this email.`,
    html: `
      <div style="font-family:Arial,sans-serif;line-height:1.5;color:#17332c">
        <h2>Reset your Skola password</h2>
        <p>Hi ${safeName},</p>
        <p>Use this secure link to choose a new Skola password.</p>
        <p><a href="${safeUrl}" style="display:inline-block;padding:10px 16px;background:#c9623d;color:#fff;text-decoration:none;border-radius:999px">Reset password</a></p>
        <p>If the button does not work, paste this URL into your browser:</p>
        <p>${safeUrl}</p>
      </div>
    `
  });
}
