import nodemailer, { type Transporter } from 'nodemailer';
import { env } from '../config/env';
import { isPlaceholderEmail } from './no-login';

/**
 * Provider-agnostic email sender, mirroring the WhatsApp lib.
 *
 * Every mail the product sends — sign-in codes, receipts, invoices raised,
 * fee reminders, notices, settlement statements, guardian invites, late
 * returns, enquiries — goes through `sendEmail`, so switching provider is a
 * matter of env.
 *
 *   EMAIL_PROVIDER=log    — the default: a dry run that logs and sends nothing
 *   EMAIL_PROVIDER=smtp   — any SMTP relay; Mailgun is the one we deploy with
 *                           (smtp.mailgun.org:587 with STARTTLS, or :465 TLS;
 *                           smtp.eu.mailgun.org for an EU domain)
 *   EMAIL_PROVIDER=resend — Resend's HTTP API
 */
export function isEmailConfigured(): boolean {
  if (!env.EMAIL_FROM) return false;
  if (env.EMAIL_PROVIDER === 'smtp') return !!env.SMTP_HOST && !!env.SMTP_USER && !!env.SMTP_PASS;
  if (env.EMAIL_PROVIDER === 'resend') return !!env.EMAIL_API_KEY;
  return false;
}

export type EmailMode = 'smtp' | 'resend' | 'log' | 'smtp-error' | 'resend-error' | 'no-login';

export interface EmailResult {
  sent: boolean;
  mode: EmailMode;
  /** Provider message id when one was returned. */
  id?: string;
}

export interface EmailAttachment {
  filename: string;
  /** Raw bytes; encoded for the provider here. */
  content: Buffer;
}

/** A send that did not go: not a dry run, a real failure the caller may surface. */
export const emailFailed = (r: EmailResult) => !r.sent && r.mode !== 'log' && r.mode !== 'no-login';

// One pooled connection per process. Mailgun rate-limits new connections far
// harder than messages on an open one, and the hourly reminder tick can send
// hundreds in a burst.
let transporter: Transporter | null = null;
function smtp(): Transporter {
  if (transporter) return transporter;
  transporter = nodemailer.createTransport({
    host: env.SMTP_HOST,
    port: env.SMTP_PORT,
    secure: env.SMTP_SECURE, // true = TLS on connect (465); false = STARTTLS (587)
    auth: { user: env.SMTP_USER, pass: env.SMTP_PASS },
    pool: true,
    maxConnections: 3,
    maxMessages: 100,
    connectionTimeout: 15_000,
    socketTimeout: 30_000,
    requireTLS: !env.SMTP_SECURE && env.SMTP_REQUIRE_TLS,
  });
  return transporter;
}

/**
 * Called once at boot when SMTP is configured: a bad password or a blocked
 * port shows up in the log at startup, not on the first reminder at 2 a.m.
 * Never throws — the server still starts and every send reports a failure.
 */
export async function verifyEmailTransport(): Promise<{ ok: boolean; detail: string }> {
  if (env.EMAIL_PROVIDER !== 'smtp') return { ok: true, detail: `email provider: ${env.EMAIL_PROVIDER}` };
  if (!isEmailConfigured()) return { ok: false, detail: 'EMAIL_PROVIDER=smtp but SMTP_HOST, SMTP_USER, SMTP_PASS or EMAIL_FROM is missing' };
  try {
    await smtp().verify();
    return { ok: true, detail: `smtp ${env.SMTP_HOST}:${env.SMTP_PORT} as ${env.SMTP_USER}` };
  } catch (err) {
    return { ok: false, detail: err instanceof Error ? err.message : String(err) };
  }
}

export async function sendEmail(
  to: string,
  subject: string,
  text: string,
  html?: string,
  attachments: EmailAttachment[] = [],
  /** Per-message Reply-To (e.g. the person a CRM email is from); else EMAIL_REPLY_TO. */
  options: { replyTo?: string } = {},
): Promise<EmailResult> {
  const replyTo = options.replyTo ?? env.EMAIL_REPLY_TO;
  // Someone registered without a login has a placeholder address. Nothing is
  // ever sent there, whatever the caller.
  if (isPlaceholderEmail(to)) return { sent: false, mode: 'no-login' };
  if (isEmailConfigured() && env.EMAIL_PROVIDER === 'smtp') {
    try {
      const info = await smtp().sendMail({
        from: env.EMAIL_FROM,
        to,
        subject,
        text,
        ...(html ? { html } : {}),
        ...(replyTo ? { replyTo } : {}),
        ...(attachments.length ? { attachments: attachments.map((a) => ({ filename: a.filename, content: a.content })) } : {}),
      });
      return { sent: true, mode: 'smtp', id: info.messageId };
    } catch (err) {
      // eslint-disable-next-line no-console
      console.error(`Email send failed (smtp) to ${to}: ${err instanceof Error ? err.message : String(err)}`);
      return { sent: false, mode: 'smtp-error' };
    }
  }
  if (isEmailConfigured() && env.EMAIL_PROVIDER === 'resend') {
    try {
      const res = await fetch('https://api.resend.com/emails', {
        method: 'POST',
        headers: { Authorization: `Bearer ${env.EMAIL_API_KEY}`, 'Content-Type': 'application/json' },
        body: JSON.stringify({
          from: env.EMAIL_FROM,
          to: [to],
          subject,
          text,
          ...(html ? { html } : {}),
          ...(replyTo ? { reply_to: replyTo } : {}),
          ...(attachments.length ? { attachments: attachments.map((a) => ({ filename: a.filename, content: a.content.toString('base64') })) } : {}),
        }),
      });
      if (!res.ok) {
        // eslint-disable-next-line no-console
        console.error(`Email send failed (${res.status}) to ${to}`);
        return { sent: false, mode: 'resend-error' };
      }
      const body = (await res.json().catch(() => ({}))) as { id?: string };
      return { sent: true, mode: 'resend', id: body.id };
    } catch {
      return { sent: false, mode: 'resend-error' };
    }
  }
  // eslint-disable-next-line no-console
  console.log(`[email dry-run] to=${to} subject="${subject}"`);
  return { sent: false, mode: 'log' };
}
