import { render } from '@react-email/components';
import { fail, info } from '@zen/core/shared/logger';
import { sendEmail } from '@zen/core/email';
import { VerificationEmail } from '../templates/VerificationEmail.jsx';
import { PasswordResetEmail } from '../templates/PasswordResetEmail.jsx';
import { PasswordChangedEmail } from '../templates/PasswordChangedEmail.jsx';

export { createEmailVerification, verifyEmailToken, createPasswordReset, verifyResetToken, deleteResetToken }
  from '../../../core/users/verifications.js';

async function sendVerificationEmail(email, token, baseUrl) {
  const appName = process.env.ZEN_NAME || 'ZEN';
  const verificationUrl = `${baseUrl}/auth/confirm?email=${encodeURIComponent(email)}&token=${token}`;
  const html = await render(<VerificationEmail verificationUrl={verificationUrl} companyName={appName} />);
  const result = await sendEmail({ to: email, subject: `Confirmez votre adresse courriel – ${appName}`, html });
  if (!result.success) {
    fail(`Auth: failed to send verification email to ${email}: ${result.error}`);
    throw new Error('Failed to send verification email');
  }
  info(`Auth: verification email sent to ${email}`);
  return result;
}

async function sendPasswordResetEmail(email, token, baseUrl) {
  const appName = process.env.ZEN_NAME || 'ZEN';
  const resetUrl = `${baseUrl}/auth/reset?email=${encodeURIComponent(email)}&token=${token}`;
  const html = await render(<PasswordResetEmail resetUrl={resetUrl} companyName={appName} />);
  const result = await sendEmail({ to: email, subject: `Réinitialisation du mot de passe – ${appName}`, html });
  if (!result.success) {
    fail(`Auth: failed to send password reset email to ${email}: ${result.error}`);
    throw new Error('Failed to send password reset email');
  }
  info(`Auth: password reset email sent to ${email}`);
  return result;
}

async function sendPasswordChangedEmail(email) {
  const appName = process.env.ZEN_NAME || 'ZEN';
  const html = await render(<PasswordChangedEmail email={email} companyName={appName} />);
  const result = await sendEmail({ to: email, subject: `Mot de passe modifié – ${appName}`, html });
  if (!result.success) {
    fail(`Auth: failed to send password changed email to ${email}: ${result.error}`);
    throw new Error('Failed to send password changed email');
  }
  info(`Auth: password changed email sent to ${email}`);
  return result;
}

export { sendVerificationEmail, sendPasswordResetEmail, sendPasswordChangedEmail };
