/**
 * Payload Email Adapter
 *
 * Integriert den Multi-Tenant E-Mail-Service in Payloads Built-in Email-System.
 * Damit nutzen alle CMS-eigenen Mails (Auth, Passwort-Reset, etc.) automatisch
 * den Tenant-spezifischen SMTP.
 */

import type { EmailAdapter, SendEmailOptions as PayloadSendEmailOptions } from 'payload'
import nodemailer from 'nodemailer'
import type { Transporter } from 'nodemailer'

// Cache für den globalen Transporter
let globalTransporter: Transporter | null = null

/**
 * Erstellt den globalen SMTP-Transporter
 */
function getGlobalTransporter(): Transporter {
  if (!globalTransporter) {
    globalTransporter = nodemailer.createTransport({
      host: process.env.SMTP_HOST || 'localhost',
      port: parseInt(process.env.SMTP_PORT || '587'),
      secure: process.env.SMTP_SECURE === 'true',
      auth:
        process.env.SMTP_USER && process.env.SMTP_PASS
          ? {
              user: process.env.SMTP_USER,
              pass: process.env.SMTP_PASS,
            }
          : undefined,
    })
  }
  return globalTransporter
}

/**
 * Multi-Tenant Email Adapter für Payload CMS
 *
 * Dieser Adapter wird für System-E-Mails (Auth, Passwort-Reset) verwendet.
 * Er nutzt die globale SMTP-Konfiguration als Fallback.
 *
 * Für Tenant-spezifische E-Mails sollte weiterhin sendTenantEmail() verwendet werden.
 */
export const multiTenantEmailAdapter: EmailAdapter = () => {
  const fromAddress = process.env.SMTP_FROM_ADDRESS || 'noreply@c2sgmbh.de'
  const fromName = process.env.SMTP_FROM_NAME || 'Payload CMS'

  return {
    name: 'multi-tenant-nodemailer',
    defaultFromAddress: fromAddress,
    defaultFromName: fromName,

    sendEmail: async (args: PayloadSendEmailOptions): Promise<void> => {
      const transporter = getGlobalTransporter()

      try {
        const result = await transporter.sendMail({
          from: args.from || `"${fromName}" <${fromAddress}>`,
          to: args.to,
          subject: args.subject,
          html: args.html,
          text: args.text,
        })

        console.log(`[Email:Payload] Sent to ${args.to}: ${result.messageId}`)
      } catch (error) {
        console.error('[Email:Payload] Error sending email:', error)
        throw error
      }
    },
  }
}

/**
 * Prüft ob SMTP konfiguriert ist
 */
export function isSmtpConfigured(): boolean {
  return Boolean(process.env.SMTP_HOST && process.env.SMTP_USER && process.env.SMTP_PASS)
}
