import { createServerFn } from "@tanstack/react-start";
import { z } from "zod";
import { sendWebsiteEmail } from "./email.server";

const applicationSchema = z.object({
  name: z.string().trim().min(1).max(100),
  email: z.string().trim().email().max(255),
  phone: z.string().trim().min(1).max(40),
  area: z.string().trim().min(1).max(120),
  message: z.string().trim().max(2000).optional(),
  attachment: z.object({
    filename: z.string().trim().min(1).max(255),
    content: z.string().max(8_000_000),
  }),
});

function escapeHtml(value: string) {
  return value
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}

export const submitCareerApplication = createServerFn({ method: "POST" })
  .validator((data: unknown) => applicationSchema.parse(data))
  .handler(async ({ data }) => {
    const html = `
      <div style="font-family:Arial,sans-serif;color:#111">
        <h2 style="margin:0 0 16px">Career application</h2>
        <p><strong>Name:</strong> ${escapeHtml(data.name)}</p>
        <p><strong>Email:</strong> ${escapeHtml(data.email)}</p>
        <p><strong>Phone:</strong> ${escapeHtml(data.phone)}</p>
        <p><strong>Area of interest:</strong> ${escapeHtml(data.area)}</p>
        <h3 style="margin:24px 0 8px">Applicant note</h3>
        <p style="white-space:pre-wrap;line-height:1.6">${escapeHtml(data.message || "Not provided")}</p>
        <p style="font-size:12px;color:#666;margin-top:24px">CV attached: ${escapeHtml(data.attachment.filename)}</p>
      </div>`;

    try {
      await sendWebsiteEmail({
        to: "info@turkysgroup.co.tz",
        replyTo: data.email,
        subject: `[Career application] ${data.area} — ${data.name}`,
        html,
        attachments: [data.attachment],
      });
    } catch (error) {
      console.error("[careers] SMTP delivery failed", error);
      throw new Error("Unable to submit your application right now. Please try again later.");
    }

    return { delivered: true as const };
  });
