import { Job } from 'bullmq';

import { getSmtpConfig, notificationEmailJobSchema } from '../config';
import { sendEmail } from '../email';
import { logger } from '../logger';

export async function processNotificationJob(job: Job): Promise<{ sent: boolean }> {
  if (job.name !== 'send-email') {
    logger.warn({ jobName: job.name }, 'Unknown notification job');
    return { sent: false };
  }

  const payload = notificationEmailJobSchema.parse(job.data);
  const config = getSmtpConfig();

  let html: string;
  if (payload.type === 'email_verification') {
    const verifyUrl = String(payload.data['verifyUrl'] ?? '');
    html = `<p>Welcome to ${config.APP_NAME}!</p><p><a href="${verifyUrl}">Verify your email address</a></p><p>This link expires in 24 hours.</p>`;
  } else {
    const resetUrl = String(payload.data['resetUrl'] ?? '');
    html = `<p>You requested a password reset for ${config.APP_NAME}.</p><p><a href="${resetUrl}">Set a new password</a></p><p>If you did not request this, ignore this email.</p>`;
  }

  await sendEmail({
    to: payload.to,
    subject: payload.subject,
    html,
  });

  logger.info({ to: payload.to, type: payload.type, jobId: job.id }, 'Email sent');
  return { sent: true };
}
