
import nodemailer from 'nodemailer';
import handlebars from 'handlebars';
import path from 'path';
import fs from 'fs';
import dotenv from 'dotenv';
dotenv.config();

export const sendAdhocMail = async ({
    taskTitle,
    firstName,
    description,
    clientName,
    projectName,
    taskUrl,
    recipientEmail,
    assignedBy

} : {
    taskTitle: string,
    firstName: string,
    description: string,
    clientName: string,
    projectName: string,
    taskUrl: string,
    recipientEmail: string,
    assignedBy: string
}) => {
    try {
        const templatePath = path.join( __dirname, 'taskEmailTemplate.hbs');
        const source = fs.readFileSync(templatePath, 'utf8');
        const template = handlebars.compile(source);

        // Fill the template variables
        const htmlContent = template({
            taskTitle,
            firstName,
            description,
            clientName,
            projectName,
            taskUrl,
            assignedBy
        });

        // Set up Nodemailer transporter
        const transporter = nodemailer.createTransport({
            // host: process.env.EMAIL_HOST,
            // port: process.env.EMAIL_PORT,
            service: 'Outlook365',
            auth: {
                user: process.env.EMAIL_USER,
                pass: process.env.EMAIL_PASS
            }
        });

        await transporter.sendMail({
            from: `<${process.env.EMAIL_USER}>`,
            to: recipientEmail,
            subject: `Ad-hoc task assigned by ${assignedBy}`,
            html: htmlContent
        });

    } catch (error) {
        console.error('Failed to send ad-hoc task email:', error);
    }
}
