import "server-only";
import { env } from "./env";

/** Minimal HTML escape — the `content` field accepts HTML, so escape user text. */
function escapeHtml(s: string): string {
  return s
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");
}

export interface ContactInput {
  firstName: string;
  lastName?: string;
  email: string;
  subject?: string;
  message: string;
  /** Where the message came from, stored as custom attributes. */
  source?: string;
  page?: string;
  locale?: string;
}

export interface CreatedConversation {
  uuid: string;
  reference_number: string;
}

/**
 * Create a Libredesk conversation initiated by a contact.
 * Verified required fields: content, inbox_id, contact_email, first_name, initiator.
 */
export async function createConversation(input: ContactInput): Promise<CreatedConversation> {
  const paragraphs = escapeHtml(input.message)
    .split(/\n{2,}/)
    .map((p) => `<p>${p.replace(/\n/g, "<br>")}</p>`)
    .join("");

  const body = {
    inbox_id: env.LIBREDESK_INBOX_ID,
    initiator: "contact" as const,
    contact_email: input.email,
    first_name: input.firstName,
    last_name: input.lastName ?? "",
    subject: input.subject?.trim() || "Contact from seoinsight.app",
    content: paragraphs,
    ...(env.LIBREDESK_SUPPORT_TEAM_ID ? { team_id: env.LIBREDESK_SUPPORT_TEAM_ID } : {}),
    custom_attributes: {
      source: input.source ?? "marketing-site",
      ...(input.page ? { page: input.page } : {}),
      ...(input.locale ? { locale: input.locale } : {}),
    },
  };

  const res = await fetch(`${env.LIBRE_DESK_API_URL.replace(/\/+$/, "")}/api/v1/conversations`, {
    method: "POST",
    headers: {
      Authorization: `token ${env.LIBRE_DESK_API_KEY}:${env.LIBRE_DESK_API_SECRET}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(body),
    // Never cache a mutation.
    cache: "no-store",
  });

  const text = await res.text();
  if (!res.ok) {
    throw new Error(`Libredesk createConversation ${res.status}: ${text}`);
  }
  const json = JSON.parse(text) as {
    data?: { uuid?: string; reference_number?: string };
  };
  return {
    uuid: json.data?.uuid ?? "",
    reference_number: json.data?.reference_number ?? "",
  };
}
