import { createTransport, type Transporter } from 'nodemailer';
import { readServerSettings } from 'officerdb';

const { MAIL_TRANSPORT } = process.env;

type SmtpConfig = {
  provider: 'resend' | 'smtp' | 'mailhog';
  apiKey?: string;
  host?: string;
  port?: number;
  username?: string;
  password?: string;
  secure?: boolean;
  fromName: string;
  fromEmail: string;
};

let cachedTransport: Transporter | null = null;
let cachedConfigHash: string | null = null;

function buildTransportUrl(config: SmtpConfig): string {
  if (config.provider === 'mailhog') {
    return `smtp://${config.host ?? 'localhost'}:${config.port ?? 1025}`;
  }
  const auth = config.username ? `${encodeURIComponent(config.username)}:${encodeURIComponent(config.password ?? '')}@` : '';
  const protocol = config.secure ? 'smtps' : 'smtp';
  return `${protocol}://${auth}${config.host}:${config.port ?? 587}`;
}

type SmtpTransport = { type: 'smtp'; transport: Transporter; from: string | null };
type ResendTransport = { type: 'resend'; apiKey: string; from: string };
export type TransportResult = SmtpTransport | ResendTransport;

export async function getTransport(): Promise<TransportResult> {
  try {
    const settings = await readServerSettings();
    const smtp: SmtpConfig | undefined = settings.smtp as SmtpConfig | undefined;
    if (smtp) {
      const from = `${smtp.fromName} <${smtp.fromEmail}>`;

      if (smtp.provider === 'resend') {
        return { type: 'resend', apiKey: smtp.apiKey ?? '', from };
      }

      const hash = JSON.stringify(smtp);
      if (cachedTransport && cachedConfigHash === hash) {
        return { type: 'smtp', transport: cachedTransport, from };
      }
      const url = buildTransportUrl(smtp);
      cachedTransport = createTransport(url);
      cachedConfigHash = hash;
      return { type: 'smtp', transport: cachedTransport, from };
    }
  } catch {
    // Fall through to env var
  }

  if (MAIL_TRANSPORT) {
    if (!cachedTransport || cachedConfigHash !== 'env') {
      cachedTransport = createTransport(MAIL_TRANSPORT);
      cachedConfigHash = 'env';
    }
    return { type: 'smtp', transport: cachedTransport, from: null };
  }

  throw new Error('No email transport configured');
}
