import nodemailer from 'nodemailer';
import { logger } from '@/lib/logger';
import { getFromEmail } from '@/lib/email/from-address';

export interface ContactReplyInput {
  contactId: string;
  toEmail: string;
  toName?: string | null;
  subject: string;
  bodyHtml: string;
  bodyText?: string;
  ccEmails?: string[];
  attachments?: Array<{
    filename: string;
    url: string;
    size: number;
    mimeType: string;
  }>;
  senderName?: string;
}

export interface ContactReplyResult {
  success: boolean;
  messageId?: string;
  error?: string;
}

const SMTP_CONFIG = {
  host: process.env.SMTP_HOST || 'localhost',
  port: parseInt(process.env.SMTP_PORT || '1025'),
  secure: process.env.SMTP_SECURE === 'true',
  auth:
    process.env.SMTP_USER && process.env.SMTP_PASS
      ? {
          user: process.env.SMTP_USER,
          pass: process.env.SMTP_PASS,
        }
      : undefined,
};

const transporter = nodemailer.createTransport(SMTP_CONFIG);

export async function sendContactReply(input: ContactReplyInput): Promise<ContactReplyResult> {
  try {
    const fromEmail = getFromEmail();
    const text = input.bodyText ?? input.bodyHtml.replace(/<[^>]+>/g, ' ').trim();

    const info = await transporter.sendMail({
      from: input.senderName ? `${input.senderName} <${fromEmail}>` : fromEmail,
      to: input.toEmail,
      cc: input.ccEmails && input.ccEmails.length > 0 ? input.ccEmails : undefined,
      subject: input.subject,
      html: input.bodyHtml,
      text,
      attachments: input.attachments?.map((attachment) => ({
        filename: attachment.filename,
        path: attachment.url,
        contentType: attachment.mimeType,
      })),
    });

    logger.info('Contact reply sent', {
      contactId: input.contactId,
      to: input.toEmail,
      messageId: info.messageId,
    });

    return { success: true, messageId: info.messageId };
  } catch (error) {
    logger.error('Failed to send contact reply email', {
      contactId: input.contactId,
      error: error instanceof Error ? error.message : String(error),
    });
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Failed to send email',
    };
  }
}
