import config from "../config.js";
import * as nodemailer from "nodemailer";

import type SMTPTransport from "nodemailer/lib/smtp-transport";

export interface EmailMessage {
  to: string | string[];
  subject: string;
  text?: string;
  html?: string;
}

async function createTransporter() {
  if (
    config.emergency.isEnabled &&
    config.emergency.mail.isEnabled
  ) {
    const transporter = nodemailer.createTransport({
      host: config.emergency.mail.host,
      port: config.emergency.mail.port,
      secure: config.emergency.mail.secure,
      auth: {
        user: config.emergency.mail.user,
        pass: config.emergency.mail.password,
      },
    } as SMTPTransport.Options);

    // 接続テスト
    try {
      await transporter.verify();
      console.log("SMTPサーバーに接続できました");
    } catch (error) {
      console.error("SMTP接続テストに失敗:", error);
      throw error;
    }

    return transporter;
  }
}

export default async function sendMail(message: EmailMessage): Promise<void> {
  if (
    config.emergency.isEnabled &&
    config.emergency.mail.isEnabled
  ) {
    try {
      const transporter: any = await createTransporter();

      await transporter.sendMail({
        from: config.emergency.mail.user,
        to: Array.isArray(message.to) ? message.to.join(",") : message.to,
        subject: message.subject,
        text: message.text,
        html: message.html,
      });
      console.log("メール送信成功");
    } catch (error) {
      console.error("メール送信に失敗しました:", error);
      throw error;
    }
  } else {
    return;
  }
}
