import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { SESClient, SendEmailCommand } from '@aws-sdk/client-ses';

export interface EmailOptions {
  to: string | string[];
  subject: string;
  html: string;
  text?: string;
  cc?: string | string[];
  bcc?: string | string[];
  attachments?: Array<{
    filename: string;
    content?: Buffer | string;
    path?: string;
  }>;
}

@Injectable()
export class EmailAdapter {
  private readonly logger = new Logger(EmailAdapter.name);
  private sesClient: SESClient;
  private isConfigured: boolean = false;

  constructor(private readonly configService: ConfigService) {
    this.initializeSESClient();
  }

  private initializeSESClient() {
    const region = this.configService.get('AWS_SES_REGION');
    const accessKeyId = this.configService.get('AWS_ACCESS_KEY_ID');
    const secretAccessKey = this.configService.get('AWS_SECRET_ACCESS_KEY');

    // 检查是否配置了 AWS SES
    if (!region || !accessKeyId || !secretAccessKey) {
      this.logger.warn('AWS SES not configured. Email sending will be disabled.');
      this.isConfigured = false;
      return;
    }

    try {
      this.sesClient = new SESClient({
        region,
        credentials: {
          accessKeyId,
          secretAccessKey,
        },
      });

      this.isConfigured = true;
      this.logger.log(`AWS SES client initialized (Region: ${region})`);
    } catch (error) {
      this.logger.error('Failed to initialize AWS SES client', error);
      this.isConfigured = false;
    }
  }

  async send(options: EmailOptions): Promise<void> {
    if (!this.isConfigured) {
      this.logger.warn('AWS SES not configured. Skipping email sending.');
      return;
    }

    try {
      const fromEmail = this.configService.get('AWS_SES_FROM_EMAIL', 'noreply@ff.com');
      const fromName = this.configService.get('AWS_SES_FROM_NAME', 'FF AI Workspace');
      
      // 格式化发件人：支持带名称的格式
      // 格式: "Display Name <email@example.com>"
      const from = fromName ? `${fromName} <${fromEmail}>` : fromEmail;
      
      // 转换收件人为数组格式
      const toAddresses = Array.isArray(options.to) ? options.to : [options.to];
      const ccAddresses = options.cc 
        ? (Array.isArray(options.cc) ? options.cc : [options.cc])
        : undefined;
      const bccAddresses = options.bcc 
        ? (Array.isArray(options.bcc) ? options.bcc : [options.bcc])
        : undefined;

      // 构建 SES 邮件参数
      const params = {
        Source: from,
        Destination: {
          ToAddresses: toAddresses,
          ...(ccAddresses && { CcAddresses: ccAddresses }),
          ...(bccAddresses && { BccAddresses: bccAddresses }),
        },
        Message: {
          Subject: {
            Data: options.subject,
            Charset: 'UTF-8',
          },
          Body: {
            Html: {
              Data: options.html,
              Charset: 'UTF-8',
            },
            ...(options.text && {
              Text: {
                Data: options.text,
                Charset: 'UTF-8',
              },
            }),
          },
        },
      };

      // 发送邮件
      const command = new SendEmailCommand(params);
      const response = await this.sesClient.send(command);
      
      this.logger.log(`Email sent successfully to ${toAddresses.join(', ')} (MessageId: ${response.MessageId})`);
    } catch (error) {
      this.logger.error('Failed to send email via AWS SES', error);
      throw error;
    }
  }

  async verify(): Promise<boolean> {
    if (!this.isConfigured) {
      this.logger.warn('AWS SES not configured');
      return false;
    }

    try {
      // 使用 verifyEmailIdentity 或简单的测试发送来验证
      // AWS SES 没有直接的 verify 方法，这里我们只检查配置
      this.logger.log('AWS SES client configured and ready');
      return true;
    } catch (error) {
      this.logger.error('AWS SES verification failed', error);
      return false;
    }
  }

  private htmlToText(html: string): string {
    return html
      .replace(/<[^>]*>/g, '')
      .replace(/&nbsp;/g, ' ')
      .replace(/&amp;/g, '&')
      .replace(/&lt;/g, '<')
      .replace(/&gt;/g, '>')
      .trim();
  }
}

