/**
 * Brevo Email Service Integration (SMTP)
 * Handles email campaign delivery and transactional emails
 */

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

export interface EmailCampaignPayload {
  campaignId: string;
  subject: string;
  htmlContent: string;
  recipients: string[];
  fromEmail?: string;
  fromName?: string;
  replyTo?: string;
  trackingEnabled?: boolean;
}

export interface BrevoEmailResponse {
  success: boolean;
  messageId?: string;
  error?: string;
  timestamp: number;
}

let transporter: Transporter | null = null;

/**
 * Initialize Brevo SMTP connection
 */
export function initializeBrevo(smtpConfig: {
  host: string;
  port: number;
  user: string;
  pass: string;
}): boolean {
  try {
    transporter = nodemailer.createTransport({
      host: smtpConfig.host,
      port: smtpConfig.port,
      secure: smtpConfig.port === 465, // true for 465, false for other ports
      auth: {
        user: smtpConfig.user,
        pass: smtpConfig.pass,
      },
    });

    console.log('[Brevo] SMTP connection configured successfully');
    return true;
  } catch (error) {
    console.error('[Brevo] Failed to initialize SMTP:', error);
    return false;
  }
}

/**
 * Send email campaign to recipients
 */
export async function sendEmailCampaign(
  payload: EmailCampaignPayload
): Promise<BrevoEmailResponse> {
  if (!transporter) {
    return {
      success: false,
      error: 'Brevo SMTP not initialized',
      timestamp: Date.now(),
    };
  }

  try {
    const fromEmail = payload.fromEmail || 'noreply@playcoinkrazy.com';
    const fromName = payload.fromName || 'CoinKrazy';

    // Send to all recipients
    const mailOptions = {
      from: `${fromName} <${fromEmail}>`,
      to: payload.recipients.join(','),
      replyTo: payload.replyTo || fromEmail,
      subject: payload.subject,
      html: payload.htmlContent,
      headers: {
        'X-Campaign-ID': payload.campaignId,
      },
    };

    const info = await transporter.sendMail(mailOptions);

    console.log(
      `[Brevo] Campaign ${payload.campaignId} sent to ${payload.recipients.length} recipients. Message ID: ${info.messageId}`
    );

    return {
      success: true,
      messageId: info.messageId,
      timestamp: Date.now(),
    };
  } catch (error: any) {
    console.error('[Brevo] Failed to send campaign:', error);

    return {
      success: false,
      error: error.message || 'Unknown error',
      timestamp: Date.now(),
    };
  }
}

/**
 * Send single email
 */
export async function sendEmail(
  to: string,
  subject: string,
  htmlContent: string,
  fromEmail?: string,
  fromName?: string
): Promise<BrevoEmailResponse> {
  if (!transporter) {
    return {
      success: false,
      error: 'Brevo SMTP not initialized',
      timestamp: Date.now(),
    };
  }

  try {
    const mailOptions = {
      from: `${fromName || 'CoinKrazy'} <${fromEmail || 'noreply@playcoinkrazy.com'}>`,
      to,
      subject,
      html: htmlContent,
    };

    const info = await transporter.sendMail(mailOptions);

    console.log(`[Brevo] Email sent to ${to}. Message ID: ${info.messageId}`);

    return {
      success: true,
      messageId: info.messageId,
      timestamp: Date.now(),
    };
  } catch (error: any) {
    console.error('[Brevo] Failed to send email:', error);

    return {
      success: false,
      error: error.message || 'Unknown error',
      timestamp: Date.now(),
    };
  }
}

/**
 * Send transactional email (password reset, verification, etc.)
 */
export async function sendTransactionalEmail(
  to: string,
  subject: string,
  htmlContent: string,
  fromEmail?: string,
  fromName?: string
): Promise<BrevoEmailResponse> {
  if (!transporter) {
    return {
      success: false,
      error: 'Brevo SMTP not initialized',
      timestamp: Date.now(),
    };
  }

  try {
    const mailOptions = {
      from: `${fromName || 'CoinKrazy'} <${fromEmail || 'noreply@playcoinkrazy.com'}>`,
      to,
      subject,
      html: htmlContent,
      priority: 'high' as const,
    };

    const info = await transporter.sendMail(mailOptions);

    console.log(`[Brevo] Transactional email sent to ${to}. Message ID: ${info.messageId}`);

    return {
      success: true,
      messageId: info.messageId,
      timestamp: Date.now(),
    };
  } catch (error: any) {
    console.error('[Brevo] Failed to send transactional email:', error);

    return {
      success: false,
      error: error.message || 'Unknown error',
      timestamp: Date.now(),
    };
  }
}

/**
 * Validate email address
 */
export function validateEmail(email: string): boolean {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

/**
 * Validate email list
 */
export function validateEmailList(emails: string[]): {
  valid: string[];
  invalid: string[];
} {
  const valid: string[] = [];
  const invalid: string[] = [];

  emails.forEach((email) => {
    if (validateEmail(email)) {
      valid.push(email);
    } else {
      invalid.push(email);
    }
  });

  return { valid, invalid };
}

/**
 * Test SMTP connection
 */
export async function testConnection(): Promise<boolean> {
  if (!transporter) {
    console.error('[Brevo] SMTP not initialized');
    return false;
  }

  try {
    await transporter.verify();
    console.log('[Brevo] SMTP connection verified successfully');
    return true;
  } catch (error) {
    console.error('[Brevo] SMTP connection verification failed:', error);
    return false;
  }
}
