/**
 * Quick SMTP diagnostic. Verifies login and sends one test email to ADMIN_EMAIL.
 *   npm run mail:test
 */
import "dotenv/config";
import nodemailer from "nodemailer";

const { SMTP_HOST, SMTP_PORT, SMTP_SECURE, SMTP_USER, SMTP_PASS, SMTP_FROM, ADMIN_EMAIL } = process.env;

if (!SMTP_HOST) {
  console.error("SMTP_HOST not set. Fill in the SMTP_* values in .env first.");
  process.exit(1);
}

console.log(`Host: ${SMTP_HOST}:${SMTP_PORT} secure=${SMTP_SECURE}`);
console.log(`User: ${SMTP_USER}  (pass length: ${(SMTP_PASS || "").length})`);

const t = nodemailer.createTransport({
  host: SMTP_HOST,
  port: Number(SMTP_PORT || 587),
  secure: String(SMTP_SECURE).toLowerCase() === "true",
  auth: { user: SMTP_USER, pass: SMTP_PASS },
});

try {
  await t.verify();
  console.log("✅ Login accepted.");
  const to = ADMIN_EMAIL || SMTP_USER;
  const info = await t.sendMail({
    from: SMTP_FROM || SMTP_USER,
    to,
    subject: "W3care chat widget — SMTP test",
    text: "If you're reading this, SMTP is working. 🎉",
  });
  console.log(`✅ Test email sent to ${to} (id: ${info.messageId})`);
} catch (e) {
  console.error("❌ Failed:", e.message);
  process.exit(1);
}
