// Brevo Transactional API Client.
// Genutzt vom Auth-Hook (send-email.post.ts) für dynamic Sender-Name +
// Subject pro Mail-Typ × Locale. Replaces GoTrue's eingebauten SMTP-Sender.

import type { H3Event } from 'h3';

const BREVO_API_URL = 'https://api.brevo.com/v3/smtp/email';

interface BrevoSendParams {
  to: string;
  subject: string;
  senderName: string;
  senderEmail: string;
  htmlContent: string;
}

export async function sendBrevoMail(
  event: H3Event,
  params: BrevoSendParams,
): Promise<void> {
  const config = useRuntimeConfig(event);
  const apiKey = config.brevoApiKey as string;
  if (!apiKey) {
    throw createError({
      statusCode: 500,
      message: 'BREVO_API_KEY not configured',
    });
  }

  const body = {
    sender: { name: params.senderName, email: params.senderEmail },
    to: [{ email: params.to }],
    subject: params.subject,
    htmlContent: params.htmlContent,
  };

  const res = await fetch(BREVO_API_URL, {
    method: 'POST',
    headers: {
      'api-key': apiKey,
      accept: 'application/json',
      'content-type': 'application/json',
    },
    body: JSON.stringify(body),
  });

  if (!res.ok) {
    const errText = await res.text().catch(() => '');
    console.error(
      `[brevo] send failed status=${res.status} to=${params.to} body=${errText.slice(0, 300)}`,
    );
    throw createError({
      statusCode: 502,
      message: `Brevo API error ${res.status}`,
    });
  }
}
