// utils/mail.ts – simple wrapper around nodemailer
import nodemailer from 'nodemailer';
import { createAdminClient } from '@/lib/supabase/admin';

/**
 * Send an email using database-configured SMTP settings (or environment variable fallback).
 * @param to Recipient address
 * @param subject Subject line
 * @param text Plain‑text body
 * @param html Optional HTML body
 */
export async function sendMail({
  to,
  subject,
  text,
  html,
  attachments,
}: {
  to: string;
  subject: string;
  text: string;
  html?: string;
  attachments?: {
    filename: string;
    content: Buffer | string;
    contentType?: string;
  }[];
}) {
  // Query custom SMTP settings from database
  const supabase = createAdminClient();
  const { data: dbSettings } = await supabase
    .from('settings')
    .select('*')
    .eq('id', 'smtp')
    .maybeSingle();

  // Resolve config from DB or environment variables
  const host = dbSettings?.host || process.env.SMTP_HOST;
  const port = dbSettings?.port ? Number(dbSettings.port) : Number(process.env.SMTP_PORT);
  const secure = dbSettings 
    ? !!dbSettings.secure 
    : (process.env.SMTP_SECURE === 'true' || process.env.SMTP_SECURE === '1');
  const user = dbSettings?.user || process.env.SMTP_USER;
  const pass = dbSettings?.pass || process.env.SMTP_PASS;

  if (!host || !user) {
    throw new Error('SMTP host and user must be configured (either in settings database table or environment variables).');
  }

  // Create transporter dynamically on send request
  const transporter = nodemailer.createTransport({
    host,
    port,
    secure,
    auth: {
      user,
      pass,
    },
  });

  const info = await transporter.sendMail({
    from: user,
    to,
    subject,
    text,
    html,
    attachments,
  });

  return info;
}

