import nodemailer from 'nodemailer';
import { logOutgoingEmail } from './emailLog';

const transporter = nodemailer.createTransport({
  host: 'localhost',
  port: 25,
  secure: false,
  tls: {
    rejectUnauthorized: false,
  },
});

export interface Attachment {
  filename: string;
  content: Buffer | string;
  contentType?: string;
}

interface SendEmailOptions {
  to: string;
  subject: string;
  html: string;
  text?: string;
  attachments?: Attachment[];
  source?: string;
  kind?: string;
  orderId?: number | null;
  sentBy?: string | null;
}

export async function sendEmail(options: SendEmailOptions): Promise<void> {
  try {
    await transporter.sendMail({
      from: `"VYSTŘÍKEJ TO" <${process.env.SMTP_FROM_EMAIL || 'noreply@vystrikejto.cz'}>`,
      to: options.to,
      subject: options.subject,
      text: options.text,
      html: options.html,
      attachments: options.attachments,
    });
    await logOutgoingEmail({
      source: options.source || 'shop',
      kind: options.kind,
      recipient: options.to,
      subject: options.subject,
      html: options.html,
      text: options.text,
      orderId: options.orderId,
      sentBy: options.sentBy,
      status: 'success',
    });
  } catch (error) {
    await logOutgoingEmail({
      source: options.source || 'shop',
      kind: options.kind,
      recipient: options.to,
      subject: options.subject,
      html: options.html,
      text: options.text,
      orderId: options.orderId,
      sentBy: options.sentBy,
      status: 'failed',
      error: error instanceof Error ? error.message : String(error),
    });
    throw error;
  }
}
