import { render } from '@react-email/render';
import { getTransport } from './transport';
import { templates } from './templates';

type SendMailArgs = {
  template: string;
  subject: string;
  to: string;
  data?: any;
  from?: string;
};

export async function sendMail({ template, subject, to, data, from }: SendMailArgs) {
  const result = await getTransport();
  const sender = from ?? result.from ?? 'officerdev <no-reply@officer.dev>';

  const theTemplate = templates[template];
  const templated = theTemplate(data);

  const emailHtml = await render(templated);

  if (result.type === 'resend') {
    const res = await fetch('https://api.resend.com/emails', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${result.apiKey}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ from: sender, to, subject, html: emailHtml }),
    });
    if (!res.ok) {
      const err = await res.json();
      throw new Error(err.message ?? `Resend API error: ${res.status}`);
    }
    return;
  }

  await result.transport.sendMail({ from: sender, to, subject, html: emailHtml });
}

export { getTransport, templates };
export type { TransportResult } from './transport';
