import fs from 'fs';
import Handlebars from 'handlebars';
import { nodemailerMailService } from '../services/mailService';
import IMailService from '../declarations/mailServiceInterface';
import INotificationService, {
    NotificationResponse,
} from '../declarations/notificationServiceInterface';
import EnvVariableHelper from '../utils/envVariableHelper';
import Logger from '../utils/logger';
import { CustomerType } from '../declarations/validations';

export default class MailController implements INotificationService {
    constructor(
        // eslint-disable-next-line no-unused-vars
        private mailService: IMailService = nodemailerMailService
    ) {}

    async sendWelcomeCustomerNotification(data: {
        user: {
            username: string;
            password: string;
            mail: string;
            profile: CustomerType;
        };
    }): Promise<NotificationResponse> {
        const mail = {
            to: data.user.mail as string,
            subject: `Welcome to CineShare!`,
            text: `Hi ${data.user.profile.firstname} ${data.user.profile.lastname} \n You were invited to join the CineShare family! Here is your initial password: ${data.user.password} User your mail address ${data.user.username} as username to login.`,
            html: MailController.generateHTMLCompilerFromTemplateFile(
                EnvVariableHelper.VARIABLES.MAIL_HTML_TEMPLATE_WELCOME_CUSTOMER
            )({
                ...data,
                routes: {
                    root: `${EnvVariableHelper.VARIABLES.FRONTEND_PROTOCOL}://${EnvVariableHelper.VARIABLES.FRONTEND_HOST}:${EnvVariableHelper.VARIABLES.FRONTEND_PORT}`,
                },
            }),
        };

        return this.mailService.sendMail(mail);
    }

    static generateHTMLCompilerFromTemplateFile(templateFile: string) {
        let source;
        try {
            source = fs.readFileSync(templateFile, 'utf-8');
        } catch (e: any) {
            if (e.code === 'ENOENT') {
                Logger.sendMessage(`HTML Template ${templateFile} not found`);
            }

            return (locals: any) =>
                `Couldn't generate HTML from template to visualize the object ${JSON.stringify(
                    locals
                )}`;
        }
        return Handlebars.compile(source);
    }
}

export const nodemailerMailController = new MailController(
    nodemailerMailService
);
