import nodemailer from "nodemailer";

const transporter = nodemailer.createTransport({
  host: "smtp.mailgun.org",
  port: 587,
  secure: false,
  auth: {
    user: `postmaster@${process.env.MAILGUN_DOMAIN}`,
    pass: process.env.MAILGUN_API_KEY,
  },
});

const FROM = process.env.MAIL_FROM ?? "KC Systems <noreply@kcsystems.com>";
const APP_URL = process.env.NEXT_PUBLIC_APP_URL ?? "https://kc-systems.com";

export async function sendMail({
  to,
  subject,
  html,
}: {
  to: string;
  subject: string;
  html: string;
}) {
  await transporter.sendMail({ from: FROM, to, subject, html });
}

// ─── Templates ────────────────────────────────────────────────────────────────

export async function sendWelcomeEmail(to: string, name: string) {
  await sendMail({
    to,
    subject: "Welcome to KC Systems!",
    html: `
      <h2>Hi ${name}, welcome to KC Systems!</h2>
      <p>Your account has been created. You can now log in and explore our platform.</p>
      <p><a href="${APP_URL}/dashboard">Go to your dashboard</a></p>
    `,
  });
}

export async function sendVerificationEmail(to: string, name: string, token: string) {
  const url = `${APP_URL}/verify-email?token=${token}`;
  await sendMail({
    to,
    subject: "Verify your KC Systems email address",
    html: `
      <h2>Hi ${name}, please verify your email</h2>
      <p>Click the link below to activate your account. This link expires in 24 hours.</p>
      <p><a href="${url}" style="display:inline-block;padding:10px 24px;background:#1e3a5f;color:#fff;border-radius:8px;text-decoration:none;font-weight:600;">Verify Email</a></p>
      <p style="color:#999;font-size:12px;">If you did not create an account, you can safely ignore this email.</p>
    `,
  });
}

export async function sendPasswordResetEmail(to: string, token: string) {
  const url = `${APP_URL}/reset-password?token=${token}`;
  await sendMail({
    to,
    subject: "Reset your KC Systems password",
    html: `
      <h2>Password Reset Request</h2>
      <p>Click the link below to reset your password. This link expires in 1 hour.</p>
      <p><a href="${url}">Reset Password</a></p>
      <p>If you did not request this, please ignore this email.</p>
    `,
  });
}

export async function sendSubscriptionConfirmationEmail(
  to: string,
  name: string,
  planName: string
) {
  await sendMail({
    to,
    subject: `Subscription Confirmed — ${planName}`,
    html: `
      <h2>Hi ${name}, you're all set!</h2>
      <p>Your <strong>${planName}</strong> subscription is now active.</p>
      <p><a href="${APP_URL}/dashboard">Visit your dashboard</a></p>
    `,
  });
}
