import { Resend } from 'resend'
import nodemailer from 'nodemailer'
import type { Transporter } from 'nodemailer'

interface SendEmailOptions {
  to: string | string[]
  subject: string
  html: string
  text?: string
}

// Lazy initialization of email clients
let resendClient: Resend | null = null
let smtpTransporter: Transporter | null = null

function getResendClient() {
  if (!resendClient) {
    const config = useRuntimeConfig()
    resendClient = new Resend(config.resendApiKey)
  }
  return resendClient
}

function getSMTPTransporter() {
  if (!smtpTransporter) {
    const config = useRuntimeConfig()
    smtpTransporter = nodemailer.createTransport({
      host: config.smtpHost,
      port: Number(config.smtpPort),
      secure: config.smtpSecure === 'true',
      // Mailpit doesn't need auth
      ...(config.smtpUser && config.smtpPassword
        ? {
            auth: {
              user: config.smtpUser,
              pass: config.smtpPassword
            }
          }
        : {})
    })
  }
  return smtpTransporter
}

/**
 * Send an email using Resend or SMTP
 */
export async function sendEmail({ to, subject, html, text }: SendEmailOptions) {
  const config = useRuntimeConfig()

  // Email configuration
  const FROM_EMAIL = config.fromEmail || 'noreply@yourdomain.com'
  // Mock mode is enabled if:
  // 1. mockEmail is explicitly set to 'true', OR
  // 2. resendApiKey is not configured AND no SMTP is configured (unless mockEmail is explicitly 'false')
  const hasSmtp = config.smtpHost && config.smtpPort
  const isMockMode = config.mockEmail === 'true' || (config.mockEmail !== 'false' && !config.resendApiKey && !hasSmtp)

  try {
    // If mockEmail is enabled, log to console (development mode)
    if (isMockMode) {
      console.log('\n')
      console.log('📧 Email Mock Mode - Email would be sent:')
      console.table({
        From: FROM_EMAIL,
        To: Array.isArray(to) ? to.join(', ') : to,
        Subject: subject
      })

      if (text) {
        console.log('\n📝 Text Content:\n')
        console.log(text)
        console.log('\n\n--------------------------------------------------------------------------------------------------------\n\n')
      }
      return { success: true, mode: 'mock' }
    }

    // Use SMTP if configured (for E2E testing with Mailpit)
    if (hasSmtp) {
      const transporter = getSMTPTransporter()
      const info = await transporter.sendMail({
        from: FROM_EMAIL,
        to: Array.isArray(to) ? to.join(', ') : to,
        subject,
        html,
        text
      })
      console.log('📧 Email sent via SMTP:', info.messageId)
      return { success: true, data: info, mode: 'smtp' }
    }

    // Otherwise use Resend
    const resend = getResendClient()
    const { data, error } = await resend.emails.send({
      from: FROM_EMAIL,
      to: Array.isArray(to) ? to : [to],
      subject,
      html,
      text
    })

    if (error) {
      console.error('Error sending email:', error)
      throw new Error(`Failed to send email: ${error.message}`)
    }

    return { success: true, data, mode: 'resend' }
  } catch (error) {
    console.error('Email send error:', error)
    throw error
  }
}

/**
 * Send verification email
 */
export async function sendVerificationEmail(email: string, name: string, url: string) {
  const config = useRuntimeConfig()
  const APP_NAME = config.appName || 'Harmonic SaaS'

  const subject = `Verify your ${APP_NAME} account`
  const html = await renderEmailComponent('verification-email', {
    name,
    url,
    appName: APP_NAME
  })
  const text = `Welcome to ${APP_NAME}!\n\nHi ${name},\n\nThank you for signing up! Please verify your email address by clicking the link below:\n\n${url}\n\nIf you didn't create an account, you can safely ignore this email.`

  return sendEmail({ to: email, subject, html, text })
}

/**
 * Send password reset email
 */
export async function sendPasswordResetEmail(email: string, name: string, url: string) {
  const config = useRuntimeConfig()
  const APP_NAME = config.appName || 'Harmonic SaaS'

  const subject = `Reset your ${APP_NAME} password`
  const html = await renderEmailComponent('password-reset-email', {
    name,
    url,
    appName: APP_NAME
  })
  const text = `Reset Your Password\n\nHi ${name},\n\nWe received a request to reset your password. Click the link below to create a new password:\n\n${url}\n\nThis link will expire in 1 hour for security reasons.\n\nIf you didn't request a password reset, you can safely ignore this email.`

  return sendEmail({ to: email, subject, html, text })
}

/**
 * Send magic link email
 */
export async function sendMagicLinkEmail(email: string, url: string) {
  const config = useRuntimeConfig()
  const APP_NAME = config.appName || 'Harmonic SaaS'

  const subject = `Sign in to ${APP_NAME}`
  const html = await renderEmailComponent('magic-link-email', {
    url,
    appName: APP_NAME
  })
  const text = `Sign in to ${APP_NAME}\n\nClick the link below to sign in to your account:\n\n${url}\n\nThis link will expire in 15 minutes.\n\nIf you didn't request this email, you can safely ignore it.`

  return sendEmail({ to: email, subject, html, text })
}

/**
 * Send team invitation email
 */
export async function sendTeamInvitationEmail(
  email: string,
  organizationName: string,
  inviterName: string,
  url: string
) {
  const config = useRuntimeConfig()
  const APP_NAME = config.appName || 'Harmonic SaaS'

  const subject = `You've been invited to join ${organizationName} on ${APP_NAME}`
  const html = await renderEmailComponent('team-invitation-email', {
    organizationName,
    inviterName,
    url,
    appName: APP_NAME
  })
  const text = `You've Been Invited!\n\n${inviterName} has invited you to join ${organizationName} on ${APP_NAME}.\n\nClick the link below to accept the invitation:\n\n${url}\n\nThis invitation will expire in 7 days.\n\nIf you don't want to accept this invitation, you can ignore this email.`

  return sendEmail({ to: email, subject, html, text })
}
