import * as Brevo from '@getbrevo/brevo';

// Export interface so it can be used in other files if needed
export interface SendEmailProps {
  to: { email: string; name?: string }[];
  subject: string;
  htmlContent: string;
  sender?: { email: string; name: string };
  params?: Record<string, any>;
}

export class BrevoMailer {
  private apiInstance: Brevo.TransactionalEmailsApi;

  // The apiKey is now optional. If not passed, we look for it in the environment.
  constructor(apiKey?: string) {
    const resolvedKey = apiKey || process.env.BREVO_API_KEY;

    if (!resolvedKey) {
      throw new Error(
        'Brevo API Key missing. Please set BREVO_API_KEY in your .env file or pass it to the constructor.',
      );
    }

    this.apiInstance = new Brevo.TransactionalEmailsApi();
    this.apiInstance.setApiKey(
      Brevo.TransactionalEmailsApiApiKeys.apiKey,
      resolvedKey,
    );
  }

  /**
   * Sends a transactional email.
   */
  async sendEmail(props: SendEmailProps): Promise<boolean> {
    const { to, subject, htmlContent, sender, params } = props;
    const emailData = new Brevo.SendSmtpEmail();

    emailData.to = to;
    emailData.subject = subject;
    emailData.htmlContent = htmlContent;

    // Auto-fill sender from Env Vars if not provided in the call
    emailData.sender = sender || {
      email: process.env.BREVO_FROM_EMAIL || 'info@doseeafrica.com',
      name: process.env.BREVO_FROM_NAME || 'DOSEE AFRICA',
    };

    if (params) {
      emailData.params = params;
    }

    try {
      const data = await this.apiInstance.sendTransacEmail(emailData);
      console.log(`[Brevo] Email sent. ID: ${data.body.messageId}`);
      return true;
    } catch (error: any) {
      // console.error(
      //   '[Brevo] Error sending email:',
      //   error.body || error.message,
      //   error,
      // );
      // We explicitly throw so the caller knows it failed
      // throw new Error(`Email sending failed: ${error}`);
      console.log('[Brevo] Email sending failed.', error);
    }
  }
}

// SINGLETON EXPORT
// This creates a single instance that you can reuse everywhere in your app.
// It will automatically grab process.env.BREVO_API_KEY.
export const brevoMailer = new BrevoMailer();
