import { TRPCError } from "@trpc/server";
import { z } from "zod";

import { createTRPCRouter, publicProcedure } from "~/server/api/trpc";

export const contactRouter = createTRPCRouter({
  submit: publicProcedure
    .input(
      z.object({
        name: z.string().trim().min(1, "Please enter your name").max(200),
        email: z.string().trim().email("Please enter a valid email").max(320),
        company: z.string().trim().max(200).optional(),
        message: z
          .string()
          .trim()
          .min(10, "Tell me a little more about what you need")
          .max(5000),
        // Honeypot: hidden from real users, tempting to bots. Left empty by humans.
        website: z.string().max(0).optional().or(z.string()),
      }),
    )
    .mutation(async ({ input }) => {
      // If the honeypot is filled, silently accept and send nothing.
      if (input.website && input.website.length > 0) {
        return { ok: true as const };
      }

      try {
        // Lazy import keeps nodemailer in the server execution path only.
        const { sendContactEmail } = await import("~/server/mail");
        await sendContactEmail({
          name: input.name,
          email: input.email,
          company: input.company ?? null,
          message: input.message,
        });
      } catch (err) {
        console.error("[contact] failed to send email:", err);
        throw new TRPCError({
          code: "INTERNAL_SERVER_ERROR",
          message: "Could not send your message. Please try again.",
        });
      }

      return { ok: true as const };
    }),
});
