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

const reportSchema = z.object({
  name: z.string().trim().max(100).optional(),
  email: z.string().trim().max(255).optional(),
  phone: z.string().trim().max(40).optional(),
  subject: z.string().trim().min(1).max(150),
  category: z.string().trim().min(1).max(120),
  description: z.string().trim().min(1).max(5000),
  attachment: z
    .object({
      filename: z.string().trim().min(1).max(255),
      content: z.string().max(8_000_000),
    })
    .nullish(),
});

export type WhistleblowerReport = z.infer<typeof reportSchema>;

const RECIPIENT = "kelvin.danson@turkysgroup.co.tz";

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

export const submitWhistleblowerReport = createServerFn({ method: "POST" })
  .validator((data: unknown) => reportSchema.parse(data))
  .handler(async ({ data }) => {
    const rows: Array<[string, string]> = [
      ["Full name", data.name || "Not provided (anonymous)"],
      ["Email address", data.email || "Not provided (anonymous)"],
      ["Phone number", data.phone || "Not provided"],
      ["Category", data.category],
      ["Subject", data.subject],
    ];

    const html = `
      <div style="font-family:Arial,sans-serif;color:#111">
        <h2 style="margin:0 0 16px">Confidential whistleblower report</h2>
        <table style="border-collapse:collapse;font-size:14px">
          ${rows
            .map(
              ([key, value]) =>
                `<tr><td style="padding:6px 16px 6px 0;font-weight:bold;vertical-align:top">${escapeHtml(
                  key,
                )}</td><td style="padding:6px 0">${escapeHtml(value)}</td></tr>`,
            )
            .join("")}
        </table>
        <h3 style="margin:24px 0 8px">Description</h3>
        <p style="white-space:pre-wrap;font-size:14px;line-height:1.6">${escapeHtml(
          data.description,
        )}</p>
        <p style="font-size:12px;color:#666;margin-top:24px">
          ${data.attachment ? `Attachment included: ${escapeHtml(data.attachment.filename)}` : "No attachment provided."}
        </p>
      </div>`;

    try {
      await sendWebsiteEmail({
        to: RECIPIENT,
        replyTo: data.email,
        subject: `[Whistleblower] ${data.category} — ${data.subject}`,
        html,
        attachments: data.attachment ? [data.attachment] : undefined,
      });
    } catch (error) {
      console.error("[whistleblower] SMTP delivery failed", error);
      throw new Error("Unable to deliver the report at this time.");
    }

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