import "server-only";

import * as nodemailer from "nodemailer";

import { env } from "~/env";

const smtpConfigured = Boolean(env.SMTP_HOST && env.CONTACT_TO);

const transporter = smtpConfigured
  ? nodemailer.createTransport({
      host: env.SMTP_HOST,
      port: env.SMTP_PORT ?? 587,
      secure: env.SMTP_SECURE === "true",
      auth:
        env.SMTP_USER && env.SMTP_PASS
          ? { user: env.SMTP_USER, pass: env.SMTP_PASS }
          : undefined,
    })
  : null;

export type ContactMessage = {
  name: string;
  email: string;
  company?: string | null;
  message: string;
};

/**
 * Forward a contact submission to the CONTACT_TO inbox over SMTP.
 * If SMTP is not configured, log the submission instead so local development still works.
 */
export async function sendContactEmail(input: ContactMessage): Promise<void> {
  const subject = `New inquiry from ${input.name}${
    input.company ? ` (${input.company})` : ""
  }`;

  const text = [
    `Name:    ${input.name}`,
    `Email:   ${input.email}`,
    input.company ? `Company: ${input.company}` : null,
    "",
    input.message,
  ]
    .filter((line) => line !== null)
    .join("\n");

  if (!transporter || !env.CONTACT_TO) {
    console.warn(
      `[contact] SMTP not configured — submission not emailed.\n${subject}\n${text}`,
    );
    return;
  }

  await transporter.sendMail({
    from: env.CONTACT_FROM ?? env.SMTP_USER ?? "no-reply@hadlock.tech",
    to: env.CONTACT_TO,
    // The reply goes straight to the person who filled out the form.
    replyTo: `${input.name} <${input.email}>`,
    subject,
    text,
  });
}
