import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as nodemailer from 'nodemailer';

export interface EmailSendResult {
  success: boolean;
  messageId?: string;
  code?: string;
  message?: string;
}

/**
 * 邮件发送服务
 *
 * 环境变量配置:
 * - EMAIL_ENABLED: 是否启用邮件发送 (true/false)
 * - EMAIL_SMTP_HOST: SMTP 服务器地址
 * - EMAIL_SMTP_PORT: SMTP 端口 (默认 465)
 * - EMAIL_SMTP_SECURE: 是否使用 SSL (默认 true)
 * - EMAIL_SMTP_USER: SMTP 用户名（发件人邮箱）
 * - EMAIL_SMTP_PASS: SMTP 密码或授权码
 * - EMAIL_FROM_NAME: 发件人名称 (默认 "榴莲皇后")
 *
 * Gmail 配置示例:
 * - EMAIL_ENABLED=true
 * - EMAIL_SMTP_HOST=smtp.gmail.com
 * - EMAIL_SMTP_PORT=465
 * - EMAIL_SMTP_SECURE=true
 * - EMAIL_SMTP_USER=your-email@gmail.com
 * - EMAIL_SMTP_PASS=xxxx xxxx xxxx xxxx  (16位应用专用密码)
 * - EMAIL_FROM_NAME=榴莲皇后
 *
 * 注意: Gmail 需要开启两步验证并生成应用专用密码:
 * 1. 登录 Google 账户 > 安全性 > 两步验证（开启）
 * 2. 安全性 > 应用专用密码 > 生成新密码
 */
@Injectable()
export class EmailService implements OnModuleInit {
  private readonly logger = new Logger(EmailService.name);
  private transporter: nodemailer.Transporter | null = null;
  private readonly enabled: boolean;
  private readonly fromEmail: string;
  private readonly fromName: string;

  constructor(private readonly configService: ConfigService) {
    this.enabled = this.configService.get('EMAIL_ENABLED') === 'true';
    this.fromEmail = this.configService.get('EMAIL_SMTP_USER', '');
    this.fromName = this.configService.get('EMAIL_FROM_NAME', '榴莲皇后');
  }

  async onModuleInit() {
    await this.initTransporter();
  }

  private async initTransporter(): Promise<void> {
    if (!this.enabled) {
      this.logger.warn('邮件服务未启用，将使用模拟模式');
      return;
    }

    const host = this.configService.get<string>('EMAIL_SMTP_HOST');
    const port = this.configService.get<number>('EMAIL_SMTP_PORT', 465);
    const secure = this.configService.get('EMAIL_SMTP_SECURE', 'true') === 'true';
    const user = this.configService.get<string>('EMAIL_SMTP_USER');
    const pass = this.configService.get<string>('EMAIL_SMTP_PASS');

    if (!host || !user || !pass) {
      this.logger.warn('邮件 SMTP 配置不完整，将使用模拟模式');
      return;
    }

    try {
      this.transporter = nodemailer.createTransport({
        host,
        port,
        secure,
        auth: {
          user,
          pass,
        },
      });

      // 验证连接
      await this.transporter.verify();
      this.logger.log(`邮件服务初始化成功: ${host}:${port}`);
    } catch (error: any) {
      this.logger.error(`邮件服务初始化失败: ${error.message}`);
      this.transporter = null;
    }
  }

  /**
   * 发送验证码邮件
   */
  async sendVerificationCode(email: string, code: string): Promise<EmailSendResult> {
    const subject = '验证码 - 榴莲皇后';
    const html = `
      <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;">
        <h2 style="color: #D4AF37; text-align: center;">榴莲皇后</h2>
        <div style="background: linear-gradient(to bottom, #FFF5E6, #FFE4B5); padding: 30px; border-radius: 10px; text-align: center;">
          <p style="color: #5D4037; font-size: 16px; margin-bottom: 20px;">您的验证码是：</p>
          <div style="background: #fff; padding: 15px 30px; border-radius: 8px; display: inline-block; border: 2px solid #D4AF37;">
            <span style="font-size: 32px; font-weight: bold; color: #D4AF37; letter-spacing: 8px;">${code}</span>
          </div>
          <p style="color: #745D43; font-size: 14px; margin-top: 20px;">验证码有效期为 5 分钟，请勿泄露给他人。</p>
        </div>
        <p style="color: #999; font-size: 12px; text-align: center; margin-top: 20px;">
          如果您没有请求此验证码，请忽略此邮件。
        </p>
      </div>
    `;

    return this.sendEmail(email, subject, html);
  }

  /**
   * 发送通用邮件
   */
  async sendEmail(
    to: string,
    subject: string,
    html: string,
  ): Promise<EmailSendResult> {
    const maskedEmail = this.maskEmail(to);
    this.logger.log(`[Email] 发送邮件到 ${maskedEmail}`);

    // 模拟模式
    if (!this.enabled || !this.transporter) {
      this.logger.warn(`[Email] 模拟模式: 邮件发送到 ${maskedEmail}, 主题: ${subject}`);
      return {
        success: true,
        messageId: 'mock-message-id',
        code: 'OK',
        message: '模拟发送成功',
      };
    }

    try {
      const result = await this.transporter.sendMail({
        from: `"${this.fromName}" <${this.fromEmail}>`,
        to,
        subject,
        html,
      });

      this.logger.log(`[Email] 发送成功: messageId=${result.messageId}`);
      return {
        success: true,
        messageId: result.messageId,
        code: 'OK',
        message: '发送成功',
      };
    } catch (error: any) {
      this.logger.error(`[Email] 发送失败: ${error.message}`);
      return {
        success: false,
        code: error.code || 'SEND_FAILED',
        message: error.message || '邮件发送失败',
      };
    }
  }

  /**
   * 脱敏邮箱地址（用于日志）
   */
  private maskEmail(email: string): string {
    const [local, domain] = email.split('@');
    if (!domain || local.length < 3) {
      return email;
    }
    const maskedLocal = local.substring(0, 2) + '***' + local.substring(local.length - 1);
    return `${maskedLocal}@${domain}`;
  }
}
