import * as nodemailer from 'nodemailer';
import * as dotenv from 'dotenv';

dotenv.config();

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

export async function createTransporter() {
    // 環境変数の値をログ出力して確認
    console.log('SMTP設定:', {
        host: process.env.SMTP_HOST,
        port: process.env.SMTP_PORT,
        secure: process.env.SMTP_SECURE,
        user: process.env.SMTP_USER
    });

    const transporter = nodemailer.createTransport({
        host: process.env.SMTP_HOST,
        port: Number(process.env.SMTP_PORT),
        secure: process.env.SMTP_SECURE === 'true',
        auth: {
            user: process.env.SMTP_USER,
            pass: process.env.SMTP_PASSWORD,
        },
        debug: process.env.DEBUG === 'true',
    });

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

    return transporter;
}

export async function sendMail(message: EmailMessage): Promise<void> {
    try{
        const transporter = await createTransporter();
        await transporter.sendMail({
            from: process.env.SMTP_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;
    }
}