/**
 * @ai-summary Email service using Resend
 * @ai-context Sends transactional emails with error handling
 */

import { Resend } from 'resend';

export class EmailService {
  private resend: Resend;
  private fromEmail: string;

  constructor() {
    const apiKey = process.env['RESEND_API_KEY'];
    if (!apiKey) {
      throw new Error('RESEND_API_KEY is not configured');
    }

    this.resend = new Resend(apiKey);
    this.fromEmail = process.env['FROM_EMAIL'] || 'noreply@motovaultpro.com';
  }

  /**
   * Send an email using Resend
   * @param to Recipient email address
   * @param subject Email subject line
   * @param html Email body (HTML format with inline styles for email client compatibility)
   * @returns Promise that resolves when email is sent
   */
  async send(to: string, subject: string, html: string): Promise<void> {
    try {
      await this.resend.emails.send({
        from: this.fromEmail,
        to,
        subject,
        html,
      });
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      throw new Error(`Failed to send email: ${errorMessage}`);
    }
  }
}
