import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { SendMailClient } from "zeptomail";

export interface EmailOptions {
  to: string;
  subject: string;
  text?: string;
  html: string;
  from?: string;
  fromName?: string;
}

export interface EmailResponse {
  success: boolean;
  messageId?: string;
  error?: string;
}

export interface ProviderInfo {
  provider: string;
  configured: boolean;
  note?: string;
}

/**
 * MailService - Email sending service
 * This service handles email sending and can be configured to use different providers
 * Currently using ZeptoMail, but can be easily switched to other providers
 */
@Injectable()
export class MailService {
  private readonly logger = new Logger(MailService.name);
  private zeptoClient: SendMailClient;

  constructor(private configService: ConfigService) {
    const url = this.configService.get<string>('MAIL_URL') || '';
    const key = this.configService.get<string>('MAIL_KEY') || '';
    const token = key;
    
    this.zeptoClient = new SendMailClient({ url, token });
    this.logger.log('Mail service initialized with ZeptoMail');
  }

  /**
   * Send email using ZeptoMail
   */
  async sendEmail(options: EmailOptions): Promise<EmailResponse> {
    try {
      return await this.sendViaZeptoMail(options);
    } catch (error) {
      this.logger.error(`Failed to send email to ${options.to}`, error.stack);
      console.dir(error, { depth: null });
      return { success: false, error: error.message };
    }
  }

  /**
   * Send email via ZeptoMail
   */
  private async sendViaZeptoMail(options: EmailOptions): Promise<EmailResponse> {
    try {
      const fromAddress = options.from || this.configService.get<string>('MAIL_FROM_EMAIL') || 'noreply@app.com';
      const fromName = options.fromName || this.configService.get<string>('MAIL_FROM_NAME') || 'App';

      const response = await this.zeptoClient.sendMail({
        from: {
          address: fromAddress,
          name: fromName
        },
        to: [
          {
            email_address: {
              address: options.to,
              name: options.to.split('@')[0] // Use part before @ as name
            }
          }
        ],
        subject: options.subject,
        htmlbody: options.html
      });

      this.logger.log(`Email sent successfully to ${options.to} via ZeptoMail`);
      return { success: true, messageId: JSON.stringify(response) };
    } catch (error) {
      console.log(error);
      // this.logger.error(`ZeptoMail send failed for ${options.to}`, error.stack);
      throw error;
    }
  }

}
