import nodemailer from "nodemailer";

import { env } from "../../config/env.js";
import { HttpError } from "../../lib/http-error.js";

const getTransporter = () => {
  if (!env.SMTP_HOST || !env.SMTP_USER || !env.SMTP_PASSWORD) {
    throw new HttpError(500, "SMTP nie jest skonfigurowane");
  }

  return nodemailer.createTransport({
    host: env.SMTP_HOST,
    port: env.SMTP_PORT,
    secure: env.SMTP_SECURE,
    auth: {
      user: env.SMTP_USER,
      pass: env.SMTP_PASSWORD,
    },
  });
};

export const sendTrackingTestEmail = async () => {
  const transporter = getTransporter();
  const from = env.SMTP_FROM ?? env.SMTP_USER!;
  const sentAt = new Date().toLocaleString("pl-PL", {
    dateStyle: "short",
    timeStyle: "medium",
  });

  const result = await transporter.sendMail({
    from: `"VISAU AUTOTRACKING" <${from}>`,
    to: env.TEST_MAIL_RECIPIENT,
    subject: "VISAU TRACKING: test wysyłki maila",
    text: [
      "To jest testowy mail z panelu VISAU TRACKING.",
      "",
      `Czas wysyłki: ${sentAt}`,
      "Jeśli dostałeś tę wiadomość, konfiguracja SMTP działa poprawnie.",
    ].join("\n"),
    html: `
      <div style="font-family:Arial,sans-serif;background:#0b1220;color:#e8eefc;padding:24px">
        <div style="max-width:560px;margin:0 auto;border:1px solid rgba(88,255,125,.35);border-radius:18px;padding:24px;background:#121b2b">
          <div style="font-size:13px;letter-spacing:.22em;text-transform:uppercase;color:#78caff;margin-bottom:10px">VISAU AUTOTRACKING</div>
          <div style="font-size:24px;font-weight:700;color:#ffffff;margin-bottom:14px">Test wysyłki maila</div>
          <div style="font-size:15px;line-height:1.6;color:#c9d6ef">
            To jest testowy mail z panelu <strong>VISAU TRACKING</strong>.<br />
            Czas wysyłki: <strong>${sentAt}</strong><br />
            Jeśli dostałeś tę wiadomość, konfiguracja SMTP działa poprawnie.
          </div>
        </div>
      </div>
    `,
  });

  return {
    accepted: result.accepted,
    rejected: result.rejected,
    messageId: result.messageId,
  };
};
