/**
 * Email Action Service
 *
 * Bridges the automation engine's SendEmailHandler to the email provider system.
 * Resolves the configured provider (Brevo, Mailchimp, or Zoho) from workflow settings
 * and delegates email sending through the appropriate provider.
 *
 * Strategy:
 * - Brevo: Uses SMTP transactional API for single emails (fast, direct)
 * - Mailchimp: Creates a single-recipient campaign and sends it
 * - Zoho: Creates a single-recipient campaign and sends it
 */

import { emailIntegrationService } from '../email/EmailIntegrationService';
import type { EmailProviderService, SenderResult } from '../email/EmailProviderService';

export interface SendWorkflowEmailParams {
  companyId: string;
  provider?: 'brevo' | 'mailchimp' | 'zoho';
  to: string;
  subject: string;
  htmlContent?: string;
  htmlUrl?: string;
  templateId?: number;
  senderId?: number;
  senderEmail?: string;
  senderName?: string;
  replyTo?: string;
  listIds?: number[];
}

export interface SendWorkflowEmailResult {
  success: boolean;
  messageId?: string;
  campaignId?: string | number;
  error?: string;
}

export class EmailActionService {

  /**
   * Send an email through the workflow's configured email provider.
   * Falls back to the first connected provider if no specific provider is set.
   */
  async sendWorkflowEmail(params: SendWorkflowEmailParams): Promise<SendWorkflowEmailResult> {
    try {
      // 1. Resolve provider
      const provider = await this.resolveProvider(params.companyId, params.provider);
      if (!provider) {
        return {
          success: false,
          error: `No email provider connected${params.provider ? ` (${params.provider})` : ''}. Connect one in Settings > Email Integration.`,
        };
      }

      // 2. Resolve sender
      const sender = await this.resolveSender(provider, params);
      if (!sender) {
        return {
          success: false,
          error: 'No sender configured. Add a sender in Settings > Email Integration.',
        };
      }

      // 3. Send via provider's transactional email method
      const result = await provider.sendTransactionalEmail({
        to: params.to,
        subject: params.subject,
        htmlContent: params.htmlContent,
        htmlUrl: params.htmlUrl,
        templateId: params.templateId,
        sender: {
          email: sender.email,
          name: sender.name,
          id: sender.id,
        },
        replyTo: params.replyTo,
        tags: ['automation'],
      });

      return result;

    } catch (error: any) {
      console.error('[EmailActionService] Error sending workflow email:', error);
      return {
        success: false,
        error: error.message || 'Failed to send email',
      };
    }
  }

  /**
   * Resolve the email provider to use
   */
  private async resolveProvider(
    companyId: string,
    providerName?: 'brevo' | 'mailchimp' | 'zoho'
  ): Promise<EmailProviderService | null> {
    try {
      return await emailIntegrationService.getProvider(companyId, providerName || undefined);
    } catch (error) {
      console.error('[EmailActionService] Error resolving provider:', error);
      return null;
    }
  }

  /**
   * Resolve sender info — use provided sender or fall back to default
   */
  private async resolveSender(
    provider: EmailProviderService,
    params: SendWorkflowEmailParams
  ): Promise<SenderResult | null> {
    // If sender details are explicitly provided in node config, use them
    if (params.senderEmail) {
      return {
        id: params.senderId || 0,
        email: params.senderEmail,
        name: params.senderName || params.senderEmail,
        active: true,
      };
    }

    // Try to get senders from the provider
    try {
      const senders = await provider.getSenders();
      // Find the first active sender
      const activeSender = senders.find(s => s.active);
      if (activeSender) {
        return activeSender;
      }
      // Fall back to the first sender if none are active
      if (senders.length > 0) {
        return senders[0];
      }
    } catch (error) {
      console.error('[EmailActionService] Error fetching senders:', error);
    }

    return null;
  }
}

// Singleton export
export const emailActionService = new EmailActionService();