import { Resend } from 'resend';
import { done, fail, info } from '@zen/core/shared/logger';

let resendClient = null;

function getResendClient() {
  if (!resendClient) {
    const apiKey = process.env.ZEN_EMAIL_RESEND_APIKEY;
    if (!apiKey) throw new Error('ZEN_EMAIL_RESEND_APIKEY environment variable is not set');
    resendClient = new Resend(apiKey);
  }
  return resendClient;
}

function resolveFrom(from, fromName) {
  const address = from || process.env.ZEN_EMAIL_FROM_ADDRESS;
  if (!address) throw new Error('ZEN_EMAIL_FROM_ADDRESS environment variable is not set');
  const name = fromName || process.env.ZEN_EMAIL_FROM_NAME;
  return name?.trim() ? `${name.trim()} <${address}>` : address;
}

function buildPayload({ to, subject, html, text, from, fromName, replyTo, attachments, tags }) {
  return {
    from: resolveFrom(from, fromName),
    to,
    subject,
    html,
    ...(text && { text }),
    ...(replyTo && { reply_to: replyTo }),
    ...(attachments && { attachments }),
    ...(tags && { tags })
  };
}

async function sendEmail(email) {
  try {
    const response = await getResendClient().emails.send(buildPayload(email));
    if (response.error) {
      fail(`Email Resend error: ${response.error.message || response.error}`);
      return { success: false, data: null, error: response.error.message || 'Failed to send email' };
    }
    info(`Email sent to ${email.to} — ID: ${response.data?.id}`);
    return { success: true, data: response.data, error: null };
  } catch (error) {
    fail(`Email send failed: ${error.message}`);
    return { success: false, data: null, error: error.message };
  }
}

async function sendBatchEmails(emails) {
  try {
    const response = await getResendClient().batch.send(emails.map(buildPayload));
    if (response.error) {
      fail(`Email batch Resend error: ${response.error.message || response.error}`);
      return { success: false, data: null, error: response.error.message || 'Failed to send batch emails' };
    }
    done(`Email batch of ${emails.length} sent`);
    return { success: true, data: response.data, error: null };
  } catch (error) {
    fail(`Email batch send failed: ${error.message}`);
    return { success: false, data: null, error: error.message };
  }
}

export { sendEmail, sendBatchEmails };
