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

const feedbackSchema = z.object({
  name: z.string().trim().max(100).optional(),
  email: z.string().trim().email().max(255).optional(),
  type: z.enum(["Suggestion", "Complaint", "Compliment", "General Feedback"]),
  message: z.string().trim().min(1).max(2000),
  rating: z.number().int().min(1).max(5).optional(),
});

const RECIPIENT = "info@turkysgroup.co.tz";

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

export const submitFeedback = createServerFn({ method: "POST" })
  .validator((data: unknown) => feedbackSchema.parse(data))
  .handler(async ({ data }) => {
    const html = `
      <div style="font-family:Arial,sans-serif;color:#111">
        <h2 style="margin:0 0 16px">Website feedback</h2>
        <p><strong>Type:</strong> ${escapeHtml(data.type)}</p>
        <p><strong>Name:</strong> ${escapeHtml(data.name || "Not provided")}</p>
        <p><strong>Email:</strong> ${escapeHtml(data.email || "Not provided")}</p>
        <p><strong>Rating:</strong> ${data.rating ? `${data.rating} out of 5` : "Not provided"}</p>
        <h3 style="margin:24px 0 8px">Message</h3>
        <p style="white-space:pre-wrap;line-height:1.6">${escapeHtml(data.message)}</p>
      </div>`;

    try {
      await sendWebsiteEmail({
        to: RECIPIENT,
        subject: `[Website feedback] ${data.type}`,
        html,
        replyTo: data.email,
      });
    } catch (error) {
      console.error("[feedback] SMTP delivery failed", error);
      throw new Error("Unable to send your feedback right now. Please try again later.");
    }

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