import * as nodemailer from 'nodemailer'
import { Injectable, Logger } from '@nestjs/common'

@Injectable()
export class EmailService {
  private readonly logger = new Logger(EmailService.name)
  private transporter: nodemailer.Transporter | null = null

  constructor() {
    this.initTransporter()
  }

  private initTransporter() {
    try {
      this.transporter = nodemailer.createTransport({
        host: process.env.EMAIL_HOST || 'smtp.qiye.aliyun.com',
        port: Number(process.env.EMAIL_PORT) || 465,
        secure: process.env.EMAIL_SECURE === 'true',
        auth: {
          user: process.env.EMAIL_USER || 'contact@yuzhiran.com',
          pass: process.env.EMAIL_PASSWORD,
        },
      })
      this.logger.log('邮件服务初始化完成')
    } catch (e) {
      this.logger.error('邮件服务初始化失败', e)
    }
  }

  async sendVerificationCode(to: string, code: string): Promise<boolean> {
    if (!this.transporter) {
      this.logger.warn('邮件服务未初始化，跳过发送')
      return false
    }
    try {
      const fromName = process.env.EMAIL_FROM || 'AI磁场 <contact@yuzhiran.com>'
      await this.transporter.sendMail({
        from: fromName,
        to,
        subject: 'AI磁场 - 登录验证码',
        html: `
          <div style="font-family: -apple-system, sans-serif; max-width: 480px; margin: 0 auto; padding: 32px;">
            <div style="text-align: center; margin-bottom: 24px;">
              <h1 style="font-size: 28px; color: #4F46E5; margin: 0;">AI 磁场</h1>
              <p style="color: #9CA3AF; font-size: 14px; margin: 4px 0 0;">您的登录验证码</p>
            </div>
            <div style="background: #F3F4F6; border-radius: 16px; padding: 32px; text-align: center;">
              <p style="font-size: 14px; color: #6B7280; margin: 0 0 16px;">请输入以下验证码完成登录</p>
              <div style="font-size: 40px; font-weight: 800; color: #4F46E5; letter-spacing: 8px; margin: 16px 0;">${code}</div>
              <p style="font-size: 12px; color: #9CA3AF; margin: 16px 0 0;">验证码 10 分钟内有效，请勿泄露给他人</p>
            </div>
            <p style="font-size: 12px; color: #D1D5DB; text-align: center; margin-top: 24px;">宇之然AI磁场 · AI 助力你的求职之路</p>
          </div>
        `,
      })
      this.logger.log(`验证码已发送至 ${to}`)
      return true
    } catch (e) {
      this.logger.error(`发送邮件失败: ${to}`, e)
      return false
    }
  }
}
