import { drizzle } from "drizzle-orm/mysql2";
import { eq } from "drizzle-orm";
import { emailConfig } from "./drizzle/schema.js";
import nodemailer from "nodemailer";

// Connexion à la base de données
const db = drizzle(process.env.DATABASE_URL);

// Récupérer la configuration SMTP
const config = await db
  .select()
  .from(emailConfig)
  .where(eq(emailConfig.active, true))
  .limit(1);

if (config.length === 0) {
  console.error("❌ Aucune configuration email active trouvée");
  process.exit(1);
}

const emailConf = config[0];

console.log("📧 Configuration SMTP trouvée:");
console.log("  Provider:", emailConf.provider);
console.log("  Mode:", emailConf.mode);
console.log("  SMTP Host:", emailConf.smtpHost);
console.log("  SMTP Port:", emailConf.smtpPort);
console.log("  SMTP Secure:", emailConf.smtpSecure);
console.log("  SMTP User:", emailConf.smtpUser);
console.log("  From Email:", emailConf.fromEmail);
console.log("  From Name:", emailConf.fromName);
console.log("");

if (emailConf.provider !== "smtp") {
  console.error("❌ Le provider n'est pas 'smtp' mais:", emailConf.provider);
  process.exit(1);
}

if (!emailConf.smtpHost || !emailConf.smtpPort || !emailConf.smtpUser || !emailConf.smtpPassword) {
  console.error("❌ Configuration SMTP incomplète");
  process.exit(1);
}

console.log("🔧 Création du transporteur SMTP...");

const transporterConfig = {
  host: emailConf.smtpHost,
  port: emailConf.smtpPort,
  secure: emailConf.smtpSecure === "ssl",
  auth: {
    user: emailConf.smtpUser,
    pass: emailConf.smtpPassword,
  },
  tls: {
    rejectUnauthorized: false,
  },
};

if (emailConf.smtpSecure === "tls") {
  transporterConfig.requireTLS = true;
}

console.log("  Config:", JSON.stringify({
  ...transporterConfig,
  auth: { user: transporterConfig.auth.user, pass: "***" }
}, null, 2));

const transporter = nodemailer.createTransport(transporterConfig);

console.log("");
console.log("🔍 Test de connexion SMTP...");

try {
  await transporter.verify();
  console.log("✅ Connexion SMTP réussie !");
} catch (error) {
  console.error("❌ Erreur de connexion SMTP:", error.message);
  console.error("Détails:", error);
  process.exit(1);
}

console.log("");
console.log("📨 Envoi d'un email de test...");

const testEmail = process.argv[2] || "test@example.com";

try {
  const info = await transporter.sendMail({
    from: `"${emailConf.fromName}" <${emailConf.fromEmail}>`,
    to: testEmail,
    subject: "Test SMTP - Formation Manager Itinova",
    html: `
      <h1>✅ Test réussi !</h1>
      <p>Cet email de test a été envoyé avec succès depuis votre configuration SMTP.</p>
      <p>Votre configuration d'envoi d'emails fonctionne correctement.</p>
      <hr>
      <p><small>Configuration: ${emailConf.smtpHost}:${emailConf.smtpPort} (${emailConf.smtpSecure})</small></p>
    `,
  });

  console.log("✅ Email envoyé avec succès !");
  console.log("  Message ID:", info.messageId);
  console.log("  Response:", info.response);
} catch (error) {
  console.error("❌ Erreur lors de l'envoi:", error.message);
  console.error("Détails:", error);
  process.exit(1);
}

console.log("");
console.log("🎉 Test terminé avec succès !");
process.exit(0);
