import { Blog } from "@/payload-types";

export function sanitizeNumber(input: string | undefined | null): number {
  if (!input) return 0;

  const sanitized = parseFloat(input.replace(/[^0-9.-]+/g, ""));

  // Check if the result is a valid number and not NaN or Infinity
  if (isNaN(sanitized) || !isFinite(sanitized)) {
    return 0;
  }

  return sanitized;
}

export function sanitizePageNumber(page: any, defaultPage = 1): number {
  const parsedPage = Number(page);

  if (isNaN(parsedPage) || parsedPage < 1 || !Number.isInteger(parsedPage)) {
    return defaultPage;
  }

  return parsedPage;
}

export function sanitizeBlogContentIntoStringPreview(data: Blog["content"], limit = 100) {
  // Find the first paragraph that has children with text
  const firstParagraph = data.root.children.find(
    (node) =>
      node.type === "paragraph" &&
      Array.isArray(node.children) &&
      node.children.length > 0 &&
      !!node.children?.[0]?.text
  );

  if (!firstParagraph) {
    return "...";
  }

  // @ts-ignore
  const text = firstParagraph.children?.[0]?.text ?? "";

  // Limit characters
  return `${text.length > limit ? text.slice(0, limit) : text}...`;
}
