import nodemailer from 'nodemailer';
import type { Account } from './imap.js';

const FETCHERPAY_SMTP_HOST = process.env['FETCHERPAY_SMTP_HOST'] ?? 'mail.fetcherpay.com';
const FETCHERPAY_SMTP_PORT = parseInt(process.env['FETCHERPAY_SMTP_PORT'] ?? '30587');

function fetcherpaySmtpTransport(user: string, pass: string) {
  return nodemailer.createTransport({
    host: FETCHERPAY_SMTP_HOST,
    port: FETCHERPAY_SMTP_PORT,
    secure: false, // STARTTLS
    auth: { user, pass },
    tls: { rejectUnauthorized: false },
  });
}

function getSmtpTransport(account: Account = 'yahoo') {
  switch (account) {
    case 'fetcherpay':
      return fetcherpaySmtpTransport(process.env['FETCHERPAY_EMAIL']!, process.env['FETCHERPAY_PASSWORD']!);
    case 'garfield':
      return fetcherpaySmtpTransport(process.env['GARFIELD_EMAIL']!, process.env['GARFIELD_PASSWORD']!);
    case 'sales':
      return fetcherpaySmtpTransport(process.env['SALES_EMAIL']!, process.env['SALES_PASSWORD']!);
    case 'leads':
      return fetcherpaySmtpTransport(process.env['LEADS_EMAIL']!, process.env['LEADS_PASSWORD']!);
    case 'founder':
      return fetcherpaySmtpTransport(process.env['FOUNDER_EMAIL']!, process.env['FOUNDER_PASSWORD']!);
    case 'gmail':
      return nodemailer.createTransport({
        host: 'smtp.gmail.com',
        port: 587,
        secure: false,
        auth: {
          user: process.env['GMAIL_EMAIL']!,
          pass: process.env['GMAIL_APP_PASSWORD']!,
        },
      });
    default:
      return nodemailer.createTransport({
        host: 'smtp.mail.yahoo.com',
        port: 587,
        secure: false,
        auth: {
          user: process.env['YAHOO_EMAIL']!,
          pass: process.env['YAHOO_APP_PASSWORD']!,
        },
      });
  }
}

function getSenderEmail(account: Account = 'yahoo'): string {
  const emailMap: Record<Account, string> = {
    yahoo:      process.env['YAHOO_EMAIL']      ?? '',
    fetcherpay: process.env['FETCHERPAY_EMAIL'] ?? '',
    garfield:   process.env['GARFIELD_EMAIL']   ?? '',
    sales:      process.env['SALES_EMAIL']      ?? '',
    leads:      process.env['LEADS_EMAIL']      ?? '',
    founder:    process.env['FOUNDER_EMAIL']    ?? '',
    gmail:      process.env['GMAIL_EMAIL']      ?? '',
  };
  return emailMap[account] ?? '';
}

export async function sendEmail(
  to: string,
  subject: string,
  body: string,
  account: Account = 'yahoo',
): Promise<string> {
  const transporter = getSmtpTransport(account);
  const info = await transporter.sendMail({
    from: getSenderEmail(account),
    to,
    subject,
    text: body,
  });
  return info.messageId;
}

export async function createDraft(
  to: string,
  subject: string,
  body: string,
  account: Account = 'yahoo',
): Promise<string> {
  const { ImapFlow } = await import('imapflow');

  const fetcherpayImapBase = {
    host: process.env['FETCHERPAY_IMAP_HOST'] ?? 'mail.fetcherpay.com',
    port: parseInt(process.env['FETCHERPAY_IMAP_PORT'] ?? '30993'),
    secure: true,
    tls: { rejectUnauthorized: false },
  };
  const fetcherpayImapAccounts: Partial<Record<Account, { user: string; pass: string }>> = {
    fetcherpay: { user: process.env['FETCHERPAY_EMAIL']!, pass: process.env['FETCHERPAY_PASSWORD']! },
    garfield:   { user: process.env['GARFIELD_EMAIL']!,   pass: process.env['GARFIELD_PASSWORD']! },
    sales:      { user: process.env['SALES_EMAIL']!,      pass: process.env['SALES_PASSWORD']! },
    leads:      { user: process.env['LEADS_EMAIL']!,      pass: process.env['LEADS_PASSWORD']! },
    founder:    { user: process.env['FOUNDER_EMAIL']!,    pass: process.env['FOUNDER_PASSWORD']! },
  };
  let imapConfig;
  if (fetcherpayImapAccounts[account]) {
    imapConfig = { ...fetcherpayImapBase, auth: fetcherpayImapAccounts[account]! };
  } else if (account === 'gmail') {
    imapConfig = {
      host: 'imap.gmail.com',
      port: 993,
      secure: true,
      auth: {
        user: process.env['GMAIL_EMAIL']!,
        pass: process.env['GMAIL_APP_PASSWORD']!,
      },
    };
  } else {
    imapConfig = {
      host: 'imap.mail.yahoo.com',
      port: 993,
      secure: true,
      auth: {
        user: process.env['YAHOO_EMAIL']!,
        pass: process.env['YAHOO_APP_PASSWORD']!,
      },
    };
  }

  const client = new ImapFlow(imapConfig);
  await client.connect();

  const from = getSenderEmail(account);
  const rawMessage = [
    `From: ${from}`,
    `To: ${to}`,
    `Subject: ${subject}`,
    `MIME-Version: 1.0`,
    `Content-Type: text/plain; charset=UTF-8`,
    ``,
    body,
  ].join('\r\n');

  await client.append('Drafts', Buffer.from(rawMessage), ['\\Draft', '\\Seen']);
  await client.logout();

  return `Draft created: "${subject}" to ${to}`;
}
