import { env } from '../config/env.js';
import logger from '../config/logger.js';

// Transactional email through Mailgun's HTTP API, using templates stored in
// Mailgun (sources in email-templates/). Uses Node's built-in fetch — no SDK.
// Without MAILGUN_API_KEY / MAILGUN_DOMAIN nothing is sent: outside production
// the email (including its link) is logged so local work isn't blocked.

const API_BASE = { us: 'https://api.mailgun.net', eu: 'https://api.eu.mailgun.net' } as const;

export interface TemplateEmail {
  to: string;
  subject: string;
  /** Mailgun template name, e.g. env.MAILGUN_TEMPLATE_INVITE. */
  template: string;
  /** Handlebars variables used by the template. */
  variables: Record<string, string | number | boolean>;
}

export const mailerConfigured = () => Boolean(env.MAILGUN_API_KEY && env.MAILGUN_DOMAIN);

/** Sends a template email. Never throws: returns false when not configured or Mailgun refuses. */
export async function sendTemplateEmail(email: TemplateEmail): Promise<boolean> {
  if (!mailerConfigured()) {
    if (env.NODE_ENV !== 'production') {
      logger.info('Email not sent (Mailgun is not configured)', { to: email.to, template: email.template, variables: email.variables });
    } else {
      logger.warn('Email not sent: Mailgun is not configured', { template: email.template });
    }
    return false;
  }

  const form = new URLSearchParams({
    from: env.MAIL_FROM || `BlenAxis <no-reply@${env.MAILGUN_DOMAIN}>`,
    to: email.to,
    subject: email.subject,
    template: email.template,
    't:variables': JSON.stringify(email.variables),
  });

  try {
    const response = await fetch(`${API_BASE[env.MAILGUN_REGION]}/v3/${env.MAILGUN_DOMAIN}/messages`, {
      method: 'POST',
      headers: {
        Authorization: `Basic ${Buffer.from(`api:${env.MAILGUN_API_KEY}`).toString('base64')}`,
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: form.toString(),
    });
    if (!response.ok) {
      logger.error('Mailgun refused the email', { status: response.status, template: email.template, body: (await response.text()).slice(0, 300) });
      return false;
    }
    const { id } = (await response.json().catch(() => ({}))) as { id?: string };
    logger.info('Email sent via Mailgun', { template: email.template, to: email.to, id });
    return true;
  } catch (error) {
    logger.error('Mailgun request failed', { template: email.template, message: error instanceof Error ? error.message : String(error) });
    return false;
  }
}
