import { Queue } from 'bullmq';
import { redisConfig } from './config.js';

export const notificationQueue = new Queue('notificationQueue', {
    connection: redisConfig
});

function buildNotificationJobId(data: {
    email?: string | null;
    templateCode?: string;
    metadata?: { entityType?: string; entityId?: string; slaDispatchKey?: string };
}): string | undefined {
    const email = data.email?.trim().toLowerCase();
    const dispatchKey = data.metadata?.slaDispatchKey;
    if (!email || !dispatchKey) return undefined;
    return `notify-${dispatchKey}-${email}`.replace(/[^a-zA-Z0-9:_-]/g, '_').slice(0, 200);
}

export const addNotificationJob = async (data: any) => {
    const jobId = buildNotificationJobId(data);
    await notificationQueue.add('sendNotification', data, {
        jobId,
        attempts: 3,
        backoff: {
            type: 'exponential',
            delay: 5000
        }
    });
};
