// src/app/mail/mail.service.ts
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { promises as fsPromises } from 'fs';
import * as nodemailer from 'nodemailer';
import * as path from 'path';
import { logger } from '..';
import createTransporter from '../../config/mails/mail.config';
import { AppConfig } from '../appConfig/AppConfig.config';

@Injectable()
export class MailService {
  private transporter: nodemailer.Transporter;

  constructor(private configService: ConfigService) {
    this.transporter = createTransporter(this.configService);
  }

  async sendMail(
    fileName: string,
    to: string,
    placeholders: Record<string, string>,
    subject = 'Email Verification',
  ): Promise<void> {
    try {
      const htmlTemplate = await this.loadTemplate(fileName, placeholders);
      logger.info(`Loaded email template for ${fileName}, to= ${to}`);
      const mailOptions = {
        from: this.configService.get<string>('mail.username'),
        to,
        subject: subject,
        html: htmlTemplate,
      };

      await this.transporter.sendMail(mailOptions);
    } catch (error) {
      logger.error('Error sending email:', error);
    }
  }

  async loadTemplate(
    templateName: string,
    placeholders: Record<string, string>,
  ): Promise<string> {
    const modifiedTemplateName = templateName?.includes('.html')
      ? templateName
      : `${templateName}.html`;

    const basePath =
      AppConfig.get('common.nodeEnv') === 'production' ? 'dist' : 'src';
    logger.info(`basePath = ${basePath}`);
    logger.info(`nodeEnv =  ${AppConfig.get('common.nodeEnv')}`);
    const templatePath = path.join(
      process.cwd(),
      basePath,
      'views',
      `${modifiedTemplateName}`,
    );

    let html: string;

    try {
      html = await fsPromises.readFile(templatePath, 'utf8');
    } catch (error) {
      console.error('Error reading template:', error);

      const defaultPath = path.join(
        process.cwd(),
        basePath,
        'views',
        'default.html',
      );
      html = await fsPromises.readFile(defaultPath, 'utf8');
    }

    Object.keys(placeholders).forEach((key) => {
      const value = placeholders[key] ?? '';
      const placeholder = `{{${key}}}`;
      html = html.split(placeholder).join(value);
    });

    return html;
  }
}
