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

/**
 * 이메일 발송 서비스 
 */
@Injectable()
export class EmailService {
  private readonly logger = new Logger(EmailService.name);
  private transporter;

  constructor(private configService: ConfigService) {
    const smtpHost = this.configService.get('SMTP_HOST');
    const smtpPort = this.configService.get('SMTP_PORT');
    const smtpUser = this.configService.get('SMTP_USER');
    const smtpPass = this.configService.get('SMTP_PASS');

    this.logger.log(`[EMAIL] SMTP 설정 초기화`);
    this.logger.log(`[EMAIL] Host: ${smtpHost}`);
    this.logger.log(`[EMAIL] Port: ${smtpPort}`);
    this.logger.log(`[EMAIL] User: ${smtpUser}`);
    this.logger.log(`[EMAIL] Pass: ${smtpPass ? '****설정됨' : '미설정!!'}`);
    process.stdout.write(`[EMAIL] SMTP Config - Host: ${smtpHost}, Port: ${smtpPort}, User: ${smtpUser}\n`);

    if (!smtpHost || !smtpPort || !smtpUser || !smtpPass) {
      this.logger.error(`[EMAIL] SMTP 설정 누락! 환경변수를 확인하세요.`);
      process.stdout.write(`[EMAIL] ERROR: SMTP 설정 누락!\n`);
    }

    this.transporter = nodemailer.createTransport({
      host: smtpHost,
      port: parseInt(smtpPort || '587'),
      secure: smtpPort === '465',
      auth: {
        user: smtpUser,
        pass: smtpPass,
      },
    });
  }

  /**
   * 인증번호 이메일 발송
   */
  async sendVerificationCode(email: string, code: string): Promise<void> {
    const fromEmail = this.configService.get('FROM_EMAIL');
    
    this.logger.log(`[EMAIL] ========== 이메일 발송 시작 ==========`);
    this.logger.log(`[EMAIL] From: ${fromEmail}`);
    this.logger.log(`[EMAIL] To: ${email}`);
    this.logger.log(`[EMAIL] Code: ${code}`);
    process.stdout.write(`[EMAIL] Sending to: ${email}, code: ${code}\n`);

    try {
      const result = await this.transporter.sendMail({
        from: fromEmail,
        to: email,
        subject: '[한우 유전능력 시스템] 인증번호 안내',
        html: `
          <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <h2 style="color: #333;">인증번호 안내</h2>
            <p>아래 인증번호를 입력해주세요.</p>
            <div style="background-color: #f5f5f5; padding: 20px; text-align: center; margin: 20px 0;">
              <h1 style="color: #4CAF50; font-size: 32px; margin: 0;">${code}</h1>
            </div>
            <p style="color: #666;">인증번호는 3분간 유효합니다.</p>
            <hr style="border: none; border-top: 1px solid #eee; margin: 20px 0;">
            <p style="color: #999; font-size: 12px;">본 메일은 발신 전용입니다.</p>
          </div>
        `,
      });

      this.logger.log(`[EMAIL] 발송 성공 - MessageId: ${result.messageId}`);
      this.logger.log(`[EMAIL] Response: ${JSON.stringify(result)}`);
      process.stdout.write(`[EMAIL] SUCCESS - MessageId: ${result.messageId}\n`);

    } catch (error) {
      this.logger.error(`[EMAIL] ========== 발송 실패 ==========`);
      this.logger.error(`[EMAIL] Error Name: ${error.name}`);
      this.logger.error(`[EMAIL] Error Message: ${error.message}`);
      this.logger.error(`[EMAIL] Error Code: ${error.code}`);
      this.logger.error(`[EMAIL] Stack: ${error.stack}`);
      process.stdout.write(`[EMAIL] ERROR: ${error.message}\n`);
      process.stdout.write(`[EMAIL] STACK: ${error.stack}\n`);
      throw error;
    }
  }
}
