/**
 * services/email.js
 *
 * Send transactional email via the pluggable transport in
 * services/emailTransport.js. Supports Resend, SMTP direct, SendGrid,
 * Mailgun, Postmark, and "file" (writes .eml to disk for local dev).
 *
 * For SMTP / no-third-party setups, set the env vars SMTP_HOST /
 * SMTP_PORT / SMTP_USER / SMTP_PASS and the email_transport table
 * falls back to smtp automatically.
 *
 * The Resend path is kept as the legacy fallback when the
 * email_transport table is empty AND RESEND_API_KEY is set — so
 * existing deployments keep working after the upgrade.
 */

'use strict';

// Avoid circular deps: keyRotator and alertBus both depend on us transitively.
let _transport = null;
let _alertBus  = null;

const { publicBaseUrl } = require('../config/publicBaseUrl');

function escapeHtml(s) {
  return String(s)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
}

function defaultFrom() {
  return `${process.env.RESEND_FROM_NAME || 'Shield'} <${process.env.RESEND_FROM_EMAIL || 'noreply@takedowns.vesamuni.com'}>`;
}

/**
 * Lowest-level send. Returns { id, provider, raw? } on success.
 * Throws on error.
 */
async function sendRaw(to, subject, text, opts = {}) {
  if (!_transport) _transport = require('./emailTransport');
  return _transport.send({
    to, subject, text,
    from: opts.from || defaultFrom(),
    html: opts.html || `<pre style="font-family:inherit">${escapeHtml(text)}</pre>`,
    replyTo: opts.replyTo || undefined,
  });
}

async function sendVerification(user, token) {
  const url = `${publicBaseUrl()}/auth/verify?token=${token}`;
  const subject = 'Verify your Shield account';
  const text = `Hi ${user.name},

Welcome to Shield. Please confirm your email by visiting:

  ${url}

This link expires in 24 hours. If you did not sign up, you can ignore this email.

— Shield`;
  return sendRaw(user.email, subject, text);
}

async function sendPasswordReset(user, token) {
  const url = `${publicBaseUrl()}/auth/reset?token=${token}`;
  const subject = 'Reset your Shield password';
  const text = `Hi ${user.name},

We received a request to reset your password. Visit the link below to choose a new one:

  ${url}

This link expires in 2 hours. If you did not request it, ignore the email.

— Shield`;
  return sendRaw(user.email, subject, text);
}

async function sendTakedownEmail({ to, subject, body, replyTo = null }) {
  return sendRaw(to, subject, body, { replyTo });
}

module.exports = { sendRaw, sendVerification, sendPasswordReset, sendTakedownEmail };
