import Logger from '../../src/config/logger.js';
import generalTemplate from '../../src/tools/mail/templates/general.js';
import jobCompletedTemplate from '../../src/tools/mail/templates/job-completed.js';
import passwordResetTemplate from '../../src/tools/mail/templates/password-reset.js';
import performanceReportTemplate from '../../src/tools/mail/templates/performance-report.js';
import welcomeTemplate from '../../src/tools/mail/templates/welcome.js';
import workerAlertTemplate from '../../src/tools/mail/templates/worker-alert.js';
import { Mail } from '../../src/tools/mail/index.js';
import { Queue } from '../../src/index.js';
import { createQueueWorker } from '../../packages/workers/src/index.js';
const looksLikeHtml = (value) => /<\s*html\b|<!doctype\b|<\s*body\b/i.test(value);
const resolveTemplateForRender = (template) => {
    const normalized = template
        .trim()
        .toLowerCase()
        .replace(/\.html$/, '');
    switch (normalized) {
        case 'welcome':
            return welcomeTemplate;
        case 'general':
            return generalTemplate;
        case 'job-completed':
            return jobCompletedTemplate;
        case 'password-reset':
            return passwordResetTemplate;
        case 'performance-report':
            return performanceReportTemplate;
        case 'worker-alert':
            return workerAlertTemplate;
        default:
            return template;
    }
};
// Helper function to build base template variables
function buildBaseVariables(payload, jobId) {
    const { to, subject } = payload;
    return {
        email: to ?? 'test@zintrust.com',
        subject: subject ?? 'Worker Notification',
        processed_at: new Date().toISOString(),
        job_id: jobId,
        timestamp: new Date().toISOString(),
        status: 'success',
    };
}
// Helper function for template with custom data
function buildTemplateWithCustomData(payload, baseVars) {
    return {
        template: payload.template, // Safe because we check in caller
        variables: {
            ...baseVars,
            ...payload.templateData,
        },
    };
}
// Helper function for template with default data
function buildTemplateWithDefaultData(payload, baseVars) {
    const { subject, body } = payload;
    return {
        template: payload.template, // Safe because we check in caller
        variables: {
            ...baseVars,
            headline: subject ?? 'Worker Notification',
            message: body ?? 'Worker job completed successfully.',
            primary_color: '#3b82f6',
        },
    };
}
// Helper function for general template
function buildGeneralTemplate(payload, baseVars) {
    const { subject, body } = payload;
    return {
        template: 'general',
        variables: {
            ...baseVars,
            headline: subject ?? 'Worker Job Completed',
            message: body ?? 'Worker job has been processed successfully.',
            primary_color: '#3b82f6',
            action_url: payload.templateData?.['action_url'] ?? null,
            action_text: payload.templateData?.['action_text'] ?? 'View Details',
        },
    };
}
// Helper function to build template variables
function buildTemplateVariables(payload, jobId) {
    const baseVars = buildBaseVariables(payload, jobId);
    if (payload.template !== null && payload.template !== undefined && payload.templateData) {
        return buildTemplateWithCustomData(payload, baseVars);
    }
    if (payload.template !== null && payload.template !== undefined) {
        return buildTemplateWithDefaultData(payload, baseVars);
    }
    return buildGeneralTemplate(payload, baseVars);
}
// Helper function to send email
async function sendEmail(payload, selectedTemplate, templateVars) {
    const { to, subject, body } = payload;
    const templateInput = looksLikeHtml(selectedTemplate)
        ? selectedTemplate
        : resolveTemplateForRender(selectedTemplate);
    // Load and render the pure email template using Mail.render()
    const htmlContent = await Mail.render({
        template: templateInput,
        variables: templateVars,
    });
    // Send email using Mail service with pure template
    const result = await Mail.send({
        to: to ?? 'test@zintrust.com',
        subject: subject ?? 'Worker Notification from ZinTrust',
        text: body ?? `Worker job completed successfully.`,
        html: htmlContent,
        from: {
            address: 'no-reply@engage.vizo.app',
            name: 'ZinTrust Worker System',
        },
    });
    Logger.info('Email sent successfully using pure template', {
        template: selectedTemplate,
        to: to ?? 'test@zintrust.com',
        messageId: result.messageId,
        driver: result.driver,
        ok: result.ok,
    });
}
// Create a simple email processor function that doesn't depend on BullMQ
// Optimized to handle both raw payload and BullMQ Job object
async function processEmailJob(arg) {
    // Unpack payload if it's a BullMQ Job
    const payload = 'data' in arg && typeof arg.data !== 'undefined'
        ? arg.data
        : arg;
    const { to, subject, template } = payload;
    const jobId = 'id' in arg && typeof arg.id === 'string'
        ? arg.id
        : `email-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
    Logger.info('Processing email job', { jobId, to, subject, template });
    try {
        // Build template variables
        // Use generic template builder that handles both custom and default
        const { template: selectedTemplate, variables: templateVars } = buildTemplateVariables(payload, jobId);
        // Send the email
        await sendEmail(payload, selectedTemplate, templateVars);
    }
    catch (error) {
        Logger.error('Failed to send email', {
            jobId,
            to: to ?? 'test@zintrust.com',
            template: template ?? 'general',
            error: error,
        });
        throw error;
    }
}
// Create the email queue worker
const emailWorkerOptions = {
    kindLabel: 'Email Job',
    defaultQueueName: 'example-mysql1',
    maxAttempts: 3,
    getLogFields: (payload) => ({
        to: payload.to,
        subject: payload.subject,
        template: payload.template ?? 'general',
    }),
    handle: processEmailJob,
};
export const EmailWorker = createQueueWorker(emailWorkerOptions);
// Export helper functions for convenience
export const EmailQueue = {
    // Add an email job to the queue
    async add(payload, queueName = 'example-mysql1') {
        return Queue.enqueue(queueName, {
            ...payload,
            timestamp: Date.now(), // For delayed execution if needed
            attempts: 0,
        });
    },
    // Process one email job
    async processOne(queueName = 'example-mysql1') {
        return EmailWorker.processOne(queueName);
    },
    // Process all email jobs in queue
    async processAll(queueName = 'example-mysql1') {
        return EmailWorker.processAll(queueName);
    },
    // Start continuous worker
    async start(queueName = 'example-mysql1') {
        void EmailWorker.startWorker({ queueName });
    },
};
// Clean exports - no conflicts
export { EmailWorker as EmailWorkerInstance };
// Default export for Worker API compatibility
export default async function emailJobProcessor(job) {
    // Delegate to the unified processor
    await processEmailJob(job);
}
export const ZinTrustProcessor = async (job) => {
    await processEmailJob(job);
};
