// email.service.ts
import { Injectable, OnModuleInit } from '@nestjs/common';
import * as nodemailer from 'nodemailer';
import * as axios from 'axios';
import * as hbs from 'nodemailer-express-handlebars';
import { join } from 'path';
import * as ejs from 'ejs';
import * as fs from 'fs';
import * as mailgunTransport from 'nodemailer-mailgun-transport';
import Content from 'twilio/lib/rest/Content';
import { emailMessages } from '../../messages/email-messages';
import { EncryptionService } from '../services/encryption/encryption.service';

@Injectable()
export class SendMailService implements OnModuleInit {
  private transporter: nodemailer.Transporter;

  // MAIL_DRIVER=smtp
  // MAIL_HOST=smtp.gmail.com
  // MAIL_PORT=587
  // MAIL_USERNAME=jay.patel.ags@gmail.com
  // MAIL_PASSWORD=cfxalyqtndqoqpxf
  // MAIL_FROM_NAME="Fast Track Fitness"
  // MAIL_ENCRYPTION=tls
  // MAIL_FROM_ADDRESS=jay.patel.ags@gmail.com
  constructor(private encryptionService: EncryptionService) { }

  async onModuleInit() {
    const password = await this.encryptionService.decrypt(process.env.MAIL_PASSWORD);

    this.transporter = nodemailer.createTransport({
      host: process.env.MAIL_HOST,
      port: parseInt(process.env.MAIL_PORT, 10),
      secure: false,
      auth: {
        user: process.env.MAIL_USERNAME,
        pass: password,
      },
      tls: {
        rejectUnauthorized: false, // Disable certificate validation
      },
    });
  }
  // const mailgunOptions = {
  //   auth: {
  //       api_key: process.env.MAILGUN_API_KEY,
  //       domain: process.env.MAILGUN_DOMAIN,
  //   },
  // };

  // this.transporter = nodemailer.createTransport(mailgunTransport(mailgunOptions));



  async sendMail(to: string, subject: string, text: string): Promise<void> {
    try {

      await this.transporter.sendMail({
        from: process.env.MAIL_FROM_ADDRESS,
        to,
        subject,
        text,
      });
      console.log('Email sent successfully');
    } catch (error) {
      console.error('Error sending email:', error);
    }
  }

  async sendMailWithTemplates(to: string, subject: string, template: string, context: any) {

    // const templatePath = `src/templates/email/${template}.ejs`;
    const templatePath = join(__dirname, '..', '..', '..', 'src', 'templates', 'email', `${template}.ejs`);

    const header = fs.readFileSync(join(__dirname, '..', '..', '..', 'src', 'templates', 'email_layouts', 'header.ejs'), 'utf-8');
    const footer = fs.readFileSync(join(__dirname, '..', '..', '..', 'src', 'templates', 'email_layouts', 'footer.ejs'), 'utf-8');

    const templateContent = fs.readFileSync(templatePath, 'utf8');

    const html = ejs.render(templateContent, {
      header: header,
      footer: footer,
      data: context.name,
      title: context.title ? context.title : null,
    });

    try {
      const mailOptions: nodemailer.SendMailOptions = {
        from: process.env.MAIL_FROM_ADDRESS,
        to,
        subject,
        html
        // context, // Variables for the template
      };

      await this.transporter.sendMail(mailOptions);

      console.log('Email sent successfully');
    } catch (error) {
      console.error('Error sending email:', error);
    }
  }

  async sendMailObjectWithTemplates(to: string, subject: string, template: string, context: any) {

    if (!to) {
      console.error('Email address is required');
      return;
    }
    // const templatePath = `src/templates/email/${template}.ejs`;
    const templatePath = join(__dirname, '..', '..', '..', 'src', 'templates', 'email', `${template}.ejs`);

    const header = fs.readFileSync(join(__dirname, '..', '..', '..', 'src', 'templates', 'email_layouts', 'header.ejs'), 'utf-8');
    const footer = fs.readFileSync(join(__dirname, '..', '..', '..', 'src', 'templates', 'email_layouts', 'footer.ejs'), 'utf-8');

    const templateContent = fs.readFileSync(templatePath, 'utf8');

    const html = ejs.render(templateContent, {
      header: header,
      footer: footer,
      context: context,
    });

    try {
      const mailOptions: nodemailer.SendMailOptions = {
        // from : '"Connector Club" <support@connector.club>',
        from: `"${process.env.MAIL_FROM_NAME}" <${process.env.MAIL_FROM_ADDRESS}>`,
        to,
        subject,
        html
        // context, // Variables for the template
      };

      await this.transporter.sendMail(mailOptions);

      console.log('Email sent successfully');
    } catch (error) {
      console.error('Error sending email:', error);
    }
  }

  async sendMailMultipleWithNameTemplates(tos: any, subject: string, template: string, context: any) {
    if (tos.length > 0) {
      for await (const to of tos) {
        if (!to) {
          console.error('Email address is required');
          continue;
        }
        context.hello_user_name = emailMessages.en.hello_user_name.replace(':user_name', to.name),
          await this.sendMailObjectWithTemplates(to.email, subject, template, context);
      }
    }
  }

  async sendMailMultipleWithTemplates(tos: any, subject: string, template: string, context: any) {
    if (tos.length > 0) {
      await this.sendMailObjectWithTemplates(tos, subject, template, context);
    }
  }

  /////
  async sendMailWithAttachment(to: string, subject: string, text: string, attachments: Array<{ filename: string, content: Buffer }>, template: string, context: any): Promise<void> {

    // const templatePath = `src/templates/email/${template}.ejs`;
    const templatePath = join(__dirname, '..', '..', '..', 'src', 'templates', 'email', `${template}.ejs`);

    const header = fs.readFileSync(join(__dirname, '..', '..', '..', 'src', 'templates', 'email_layouts', 'header.ejs'), 'utf-8');
    const footer = fs.readFileSync(join(__dirname, '..', '..', '..', 'src', 'templates', 'email_layouts', 'footer.ejs'), 'utf-8');

    const templateContent = fs.readFileSync(templatePath, 'utf8');
    console.log(context);
    const html = ejs.render(templateContent, {
      header: header,
      footer: footer,
      // data : context.name,
      // description : context.text,
      context: context,
    });

    try {
      // Define email options
      const mailOptions: nodemailer.SendMailOptions = {
        // from: 'bopgames@bopgames.com',
        from: '"Connector Club <support@connector.club>',
        to,
        subject,
        // text: text,
        html,
        attachments: attachments.map(attachment => ({
          filename: attachment.filename,
          content: attachment.content,
        })),
      };

      // Send email with attachments
      await this.transporter.sendMail(mailOptions);
      console.log('Contact Us Reply Email sent successfully...🚀');
    } catch (error) {
      console.error('Error sending email:', error);
    }
  }

  async sendMailWithImageAttachmentFromUrlArray(email: string, subject: string, text: string, imageArray: any, template: string, context: any): Promise<void> {
    try {
      // Download image from URL
      var attachmentArray = [];
      if (imageArray.length > 0) {

        for await (const res of imageArray) {
          const response = await axios.default.get(res.imageUrl, { responseType: 'arraybuffer' });

          // Create attachment object with image content
          const attachmentObject = { filename: res.imagename, content: Buffer.from(response.data, 'binary') };

          attachmentArray.push(attachmentObject);
        }
      }

      // Send email with image attachment
      await this.sendMailWithAttachment(email, subject, text, attachmentArray, template, context);
    } catch (error) {
      console.error('Error sending email with image attachment:', error);
    }
  }
}
