/**
 * Ad Ops Email Sender
 * Sends system emails via SMTP (existing config)
 * Always CCs ryan.salazar@relevantmediaproperties.com
 */

import nodemailer from 'nodemailer';

const RYAN_EMAIL = 'ryan.salazar@relevantmediaproperties.com';

function getTransporter() {
  return nodemailer.createTransport({
    host: process.env.SMTP_HOST,
    port: parseInt(process.env.SMTP_PORT || '587'),
    secure: false,
    auth: {
      user: process.env.SMTP_USER,
      pass: process.env.SMTP_PASS,
    },
  });
}

export interface SendEmailParams {
  to: string | string[];
  cc?: string | string[];
  subject: string;
  html: string;
  attachments?: { filename: string; content?: Buffer; path?: string; contentType?: string }[];
  alwaysCcRyan?: boolean;
}

export async function sendAdOpsEmail(params: SendEmailParams): Promise<{ success: boolean; error?: string }> {
  try {
    const transporter = getTransporter();

    const toAddresses = Array.isArray(params.to) ? params.to : [params.to];
    const ccAddresses = Array.isArray(params.cc) ? params.cc : params.cc ? [params.cc] : [];

    // Always CC Ryan unless explicitly disabled
    if (params.alwaysCcRyan !== false && !ccAddresses.includes(RYAN_EMAIL)) {
      ccAddresses.push(RYAN_EMAIL);
    }

    await transporter.sendMail({
      from: `"Relevant Media Properties Ad Ops" <${process.env.SMTP_FROM_EMAIL || process.env.SMTP_USER}>`,
      to: toAddresses.join(', '),
      cc: ccAddresses.length > 0 ? ccAddresses.join(', ') : undefined,
      subject: params.subject,
      html: params.html,
      attachments: params.attachments,
    });

    return { success: true };
  } catch (err: any) {
    console.error('[AdOps Email Error]', err.message);
    return { success: false, error: err.message };
  }
}

export async function sendToJeffAndRyan(params: {
  subject: string;
  html: string;
  attachments?: SendEmailParams['attachments'];
}): Promise<{ success: boolean; error?: string }> {
  return sendAdOpsEmail({
    to: 'jeff@avbeat.com',
    cc: [RYAN_EMAIL],
    subject: params.subject,
    html: params.html,
    attachments: params.attachments,
    alwaysCcRyan: false, // Already included in cc
  });
}

export async function sendToRyanOnly(params: {
  subject: string;
  html: string;
}): Promise<{ success: boolean; error?: string }> {
  return sendAdOpsEmail({
    to: RYAN_EMAIL,
    subject: params.subject,
    html: params.html,
    alwaysCcRyan: false,
  });
}
