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

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

  constructor(private configService: ConfigService) {
    console.log('Initializing EmailService...'); // Direct console log for debugging
    this.logger.log('Initializing EmailService...');

    // Load config
    const host = this.configService.get<string>('SMTP_HOST');
    const port = this.configService.get<number>('SMTP_PORT');
    const user = this.configService.get<string>('SMTP_USER');
    const pass = this.configService.get<string>('SMTP_PASS');
    this.from = this.configService.get<string>('EMAIL_FROM');

    console.log('Email Config:', { host, port, user, from: this.from }); // Direct console log
    this.logger.log('Email Config:', { host, port, user, from: this.from });

    // Create transporter with Gmail settings
    this.transporter = nodemailer.createTransport({
      // host: 'smtp.gmail.com',
      // port: 587,  // Use STARTTLS port
      // secure: false,  // Use STARTTLS
      host: host,
      port: port,
      auth: { user, pass },
      debug: true,  // Enable debug logs
      logger: true  // Enable transport level logging
    });

    // Verify connection
    this.verifyConnection();
  }

  private async verifyConnection() {
    try {
      console.log('Verifying SMTP connection...'); // Direct console log
      this.logger.log('Verifying SMTP connection...');
      
      const verification = await this.transporter.verify();
      
      console.log('SMTP connection verified successfully!', verification); // Direct console log
      this.logger.log('SMTP connection verified successfully!', verification);
    } catch (error) {
      console.error('SMTP connection failed:', error); // Direct console log
      this.logger.error('SMTP connection failed:', {
        error: error.message,
        code: error.code,
        command: error.command,
        response: error.response,
        responseCode: error.responseCode,
        stack: error.stack,
      });
      throw error;
    }
  }

  async sendWelcomeEmail(userEmail: string, username: string): Promise<void> {
    console.log(`Sending welcome email to ${userEmail}...`); // Direct console log
    this.logger.log(`Sending welcome email to ${userEmail}...`);

    const mailOptions = {
      from: `"IMK Platform" <${this.from}>`,
      to: userEmail,
      subject: 'Welcome to IMK Platform!',
      html: `
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
          <h2>Welcome to IMK Platform!</h2>
          <p>Dear ${username},</p>
          <p>Thank you for joining IMK Platform. We're excited to have you on board!</p>
          <p>You can now start using our platform to manage and share your documents securely.</p>
          <p>If you have any questions or need assistance, please don't hesitate to contact our support team.</p>
          <p>Best regards,<br>The IMK Team</p>
        </div>
      `
    };

    try {
      console.log('Attempting to send email with options:', mailOptions); // Direct console log
      this.logger.log('Attempting to send email with options:', {
        to: mailOptions.to,
        from: mailOptions.from,
        subject: mailOptions.subject
      });

      const info = await this.transporter.sendMail(mailOptions);
      
      console.log('Email sent successfully:', info); // Direct console log
      this.logger.log('Email sent successfully:', {
        messageId: info.messageId,
        response: info.response,
        accepted: info.accepted,
        rejected: info.rejected,
        envelope: info.envelope,
      });
    } catch (error) {
      console.error('Failed to send email:', error); // Direct console log
      this.logger.error('Failed to send email:', {
        error: error.message,
        code: error.code,
        command: error.command,
        response: error.response,
        responseCode: error.responseCode,
        stack: error.stack,
      });
      throw error;
    }
  }

  async sendDocumentNotification(
    userEmail: string,
    username: string,
    documentName: string,
    action: 'uploaded' | 'shared',
  ): Promise<void> {
    console.log('=== Starting document notification email process ===');
    this.logger.log('=== Starting document notification email process ===');
    console.log(`Preparing notification for ${userEmail}, document: ${documentName}, action: ${action}`);
    this.logger.log(`Preparing notification for ${userEmail}, document: ${documentName}, action: ${action}`);
    
    const actionText = action === 'uploaded' ? 'uploaded' : 'shared with you';
    const mailOptions = {
      from: `"IMK Platform" <${this.from}>`,
      to: userEmail,
      subject: `New Document ${actionText} - IMK Platform`,
      html: `
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
          <h2>New Document Notification</h2>
          <p>Dear ${username},</p>
          <p>A new document "${documentName}" has been ${actionText} on the IMK Platform.</p>
          <p>You can access this document by logging into your account.</p>
          <p>If you have any questions or concerns, please contact our support team.</p>
          <p>Best regards,<br>The IMK Team</p>
        </div>
      `,
    };

    try {
      console.log('Sending document notification email with options:', {
        to: mailOptions.to,
        from: mailOptions.from,
        subject: mailOptions.subject,
        documentName,
        action
      });
      this.logger.log('Sending document notification email with options:', {
        to: mailOptions.to,
        from: mailOptions.from,
        subject: mailOptions.subject,
        documentName,
        action
      });

      const info = await this.transporter.sendMail(mailOptions);
      
      console.log('Document notification email sent successfully:', {
        messageId: info.messageId,
        response: info.response,
        accepted: info.accepted,
        rejected: info.rejected,
        envelope: info.envelope,
      });
      this.logger.log('Document notification email sent successfully:', {
        messageId: info.messageId,
        response: info.response,
        accepted: info.accepted,
        rejected: info.rejected,
        envelope: info.envelope,
      });
    } catch (error) {
      console.error('Failed to send document notification email:', error);
      this.logger.error('Failed to send document notification email:', {
        error: error.message,
        code: error.code,
        command: error.command,
        response: error.response,
        responseCode: error.responseCode,
        stack: error.stack,
      });
      throw error;
    }
  }

  async sendPasswordResetNotification(email: string, name: string) {
    this.logger.log('Sending password reset notification email to:', email);

    const mailOptions = {
      from: this.from,
      to: email,
      subject: 'Your Password Has Been Reset',
      html: `
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
          <h2>Password Reset Notification</h2>
          <p>Hello ${name},</p>
          <p>Your password has been reset by an administrator.</p>
          <p>If you did not expect this change, please contact your administrator immediately.</p>
          <p>Best regards,<br>IMK Team</p>
        </div>
      `,
    };

    try {
      this.logger.debug('Attempting to send password reset notification...');
      const info = await this.transporter.sendMail(mailOptions);
      this.logger.log('Password reset notification sent successfully:', info.response);
      return info;
    } catch (error) {
      this.logger.error('Failed to send password reset notification:', {
        error: error.message,
        code: error.code,
        command: error.command,
        stack: error.stack,
      });
      throw error;
    }
  }

  async sendPasswordResetEmail(email: string, name: string, token: string) {
    this.logger.log('Sending password reset email to:', email);

    const resetLink = `${process.env.FRONTEND_URL}/reset-password?token=${token}`;
    const mailOptions = {
      from: this.from,
      to: email,
      subject: 'Reset Your Password - IMK Platform',
      html: `
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
          <h2>Password Reset Request</h2>
          <p>Hello ${name},</p>
          <p>We received a request to reset your password. Click the link below to set a new password:</p>
          <p>
            <a href="${resetLink}" style="
              display: inline-block;
              padding: 10px 20px;
              background-color: #4F46E5;
              color: white;
              text-decoration: none;
              border-radius: 5px;
            ">Reset Password</a>
          </p>
          <p>This link will expire in 1 hour.</p>
          <p>If you didn't request this, please ignore this email or contact support if you have concerns.</p>
          <p>Best regards,<br>IMK Team</p>
        </div>
      `,
    };

    try {
      this.logger.debug('Attempting to send password reset email...');
      const info = await this.transporter.sendMail(mailOptions);
      this.logger.log('Password reset email sent successfully:', info.response);
      return info;
    } catch (error) {
      this.logger.error('Failed to send password reset email:', {
        error: error.message,
        code: error.code,
        command: error.command,
        stack: error.stack,
      });
      throw error;
    }
  }

  async sendPasswordChangeConfirmation(email: string, name: string) {
    this.logger.log('Sending password change confirmation to:', email);

    const mailOptions = {
      from: this.from,
      to: email,
      subject: 'Password Changed Successfully - IMK Platform',
      html: `
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
          <h2>Password Changed Successfully</h2>
          <p>Hello ${name},</p>
          <p>Your password has been successfully changed.</p>
          <p>If you did not make this change, please contact our support team immediately.</p>
          <p>Best regards,<br>IMK Team</p>
        </div>
      `,
    };

    try {
      this.logger.debug('Attempting to send password change confirmation...');
      const info = await this.transporter.sendMail(mailOptions);
      this.logger.log('Password change confirmation sent successfully:', info.response);
      return info;
    } catch (error) {
      this.logger.error('Failed to send password change confirmation:', {
        error: error.message,
        code: error.code,
        command: error.command,
        stack: error.stack,
      });
      throw error;
    }
  }
} 