import { Resend } from 'resend';
import { z } from 'zod';

/**
 * Configuration d'envoi, validée au premier message et non à l'import.
 *
 * `next build` importe la configuration d'authentification pour analyser les
 * routes, et cette configuration mène ici. Valider à l'import ferait donc
 * échouer un build faute de clé d'envoi : un build n'envoie aucun mail, il n'a
 * pas à la connaître.
 *
 * Le contrôle n'est pas perdu : il se produit au premier envoi, et l'erreur
 * nomme ce qui manque.
 */
const schema = z.object({
  RESEND_API_KEY: z.string().min(1),
  MAGIC_LINK_FROM: z.string().min(1),
});

let client: Resend | undefined;
let from: string | undefined;

function ensureClient(): { client: Resend; from: string } {
  if (client && from) return { client, from };

  const parsed = schema.safeParse(process.env);

  if (!parsed.success) {
    const missing = parsed.error.issues.map((issue) => issue.path.join('.')).join(', ');
    throw new Error(
      `Envoi impossible, configuration incomplète : ${missing}. ` +
        `Aucun lien de connexion ne peut partir tant que ces variables ne sont pas renseignées.`,
    );
  }

  client = new Resend(parsed.data.RESEND_API_KEY);
  from = parsed.data.MAGIC_LINK_FROM;

  return { client, from };
}

export async function sendMagicLinkEmail(email: string, url: string): Promise<void> {
  const mailer = ensureClient();

  const { error } = await mailer.client.emails.send({
    from: mailer.from,
    to: email,
    subject: 'Your sign-in link',
    text: [
      'Here is your link to the ADVMFR knowledge base:',
      '',
      url,
      '',
      'It expires in 10 minutes and works once.',
      'If you did not ask for it, ignore this message.',
    ].join('\n'),
  });

  /*
    Resend signale ses échecs par la valeur de retour, sans lever d'exception.
    Sans ce test, un refus : clé invalide, domaine non vérifié, destinataire
    interdit, passerait pour un succès : l'application dirait « votre lien est
    parti » et rien ne serait jamais envoyé, sans la moindre trace.
  */
  if (error) {
    throw new Error(`Resend a refusé l'envoi : ${error.name}, ${error.message}`);
  }
}
