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

@Injectable()
export class EmailService {
  private readonly logger = new Logger(EmailService.name);
  private readonly smtpConfig: any;
  private readonly emailFooter: string;

  constructor(private configService: ConfigService) {
    this.emailFooter = configService.get('brand.emailFooter', '此邮件由系统自动发送');
    this.smtpConfig = {
      host: configService.get('smtp.host'),
      port: configService.get('smtp.port'),
      secure: configService.get('smtp.secure'),
      auth: configService.get('smtp.auth'),
      from: configService.get('smtp.from'),
    };
  }

  /**
   * 发送通知邮件
   */
  async sendNotificationEmail(to: string, subject: string, content: string): Promise<void> {
    // TODO: 实现真实的 SMTP 邮件发送
    // 可以使用 nodemailer 或其他邮件服务
    
    this.logger.log(`[Email] Sending notification to ${to}`);
    this.logger.log(`[Email] Subject: ${subject}`);
    this.logger.log(`[Email] Content: ${content}`);

    // 模拟发送
    // const transporter = nodemailer.createTransporter(this.smtpConfig);
    // await transporter.sendMail({
    //   from: this.smtpConfig.from,
    //   to,
    //   subject,
    //   html: content,
    // });
  }

  /**
   * 发送审批通知
   */
  async sendApprovalNotification(to: string, params: {
    approverName: string;
    documentType: string;
    documentTitle: string;
    link: string;
  }): Promise<void> {
    const { approverName, documentType, documentTitle, link } = params;
    
    const subject = `待审批：${documentType} - ${documentTitle}`;
    const content = `
      <h2>您有一个新的审批任务</h2>
      <p>尊敬的 ${approverName}，</p>
      <p>您有一个 <strong>${documentType}</strong> 需要审批：</p>
      <p><strong>${documentTitle}</strong></p>
      <p><a href="${link}">点击查看详情</a></p>
      <p>请及时处理。</p>
      <hr>
      <p style="color: #999; font-size: 12px;">${this.emailFooter}，请勿回复。</p>
    `;

    await this.sendNotificationEmail(to, subject, content);
  }

  /**
   * 发送审批结果通知
   */
  async sendApprovalResultNotification(to: string, params: {
    submitterName: string;
    documentType: string;
    documentTitle: string;
    result: 'APPROVED' | 'REJECTED';
    comment?: string;
    link: string;
  }): Promise<void> {
    const { submitterName, documentType, documentTitle, result, comment, link } = params;
    
    const resultText = result === 'APPROVED' ? '已通过' : '已驳回';
    const subject = `审批${resultText}：${documentType} - ${documentTitle}`;
    const content = `
      <h2>您的审批申请${resultText}</h2>
      <p>尊敬的 ${submitterName}，</p>
      <p>您的 <strong>${documentType}</strong> 审批${resultText}：</p>
      <p><strong>${documentTitle}</strong></p>
      ${comment ? `<p>审批意见：${comment}</p>` : ''}
      <p><a href="${link}">点击查看详情</a></p>
      <hr>
      <p style="color: #999; font-size: 12px;">${this.emailFooter}，请勿回复。</p>
    `;

    await this.sendNotificationEmail(to, subject, content);
  }
}

