/**
 * SMTP email sender для notifications-svc
 * Использует SMTP_URL (smtp://user:pass@host:port) или отдельные переменные
 */

import nodemailer from 'nodemailer';
import type { Transporter } from 'nodemailer';

const SMTP_URL = process.env.SMTP_URL ?? '';
const SMTP_FROM = process.env.SMTP_FROM ?? 'GooSeek <notifications@gooseek.local>';

let transporter: Transporter | null = null;

function getTransporter(): Transporter | null {
  if (transporter) return transporter;
  if (!SMTP_URL?.trim()) return null;
  try {
    transporter = nodemailer.createTransport(
      { url: SMTP_URL, pool: true, maxConnections: 5, maxMessages: 100 }
    );
    return transporter;
  } catch {
    return null;
  }
}

export function isSmtpConfigured(): boolean {
  return !!SMTP_URL?.trim();
}

export interface SendEmailOptions {
  to: string;
  subject: string;
  text?: string;
  html?: string;
}

export async function sendEmail(options: SendEmailOptions): Promise<boolean> {
  const transport = getTransporter();
  if (!transport) {
    return false;
  }
  const { to, subject, text, html } = options;
  if (!to?.trim() || !subject?.trim()) {
    throw new Error('to and subject are required');
  }
  const body = text ?? html ?? '';
  if (!body) {
    throw new Error('text or html is required');
  }
  try {
    await transport.sendMail({
      from: SMTP_FROM,
      to: to.trim(),
      subject: subject.trim(),
      text: text?.trim(),
      html: html?.trim() || undefined,
    });
    return true;
  } catch (err) {
    throw err;
  }
}
