/**
 * Replace the current Nodemailer call with this helper after the PHP endpoint
 * has been uploaded to the Veritas server.
 *
 * Store PHP_MAILER_URL and PHP_MAILER_TOKEN as AppDeploy backend secrets.
 */

import { secrets } from '@appdeploy/sdk';

export async function sendThroughVeritasPhpMailer(
  form: Record<string, unknown>,
  reference: string,
  submittedAt: string
): Promise<void> {
  const mailerUrl = await secrets.readSecret('PHP_MAILER_URL');
  const mailerToken = await secrets.readSecret('PHP_MAILER_TOKEN');

  const response = await fetch(mailerUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Form-Token': mailerToken,
    },
    body: JSON.stringify({
      ...form,
      reference,
      submittedAt,
    }),
  });

  const result = await response.json().catch(() => ({})) as {
    success?: boolean;
    message?: string;
  };

  if (!response.ok || result.success !== true) {
    throw new Error(result.message || 'PHP mail gateway rejected the request.');
  }
}
