import { Blog } from "@/payload-types";
import { BlogData } from "@/schema/blog";
import { FetchBlogParams, FetchRecentBlogParams } from "@/schema/services/blog";
import { formatDate } from "@/utils/datetime";
import { sanitizeBlogContentIntoStringPreview } from "@/utils/sanitize";
import { PaginatedDocs, Where } from "payload";
import { stringify } from "qs-esm";

export async function fetchBlogREST({ page, search = "", categoryId, tagId }: FetchBlogParams = {}) {
  const queryCondition: Where = {
    _status: { equals: "published" },
  };

  if (!!search) {
    queryCondition["title"] = {
      contains: search,
    };
  }
  if (!!categoryId) {
    queryCondition["categories"] = {
      equals: categoryId,
    };
  }
  if (!!tagId) {
    queryCondition["tags"] = {
      equals: tagId,
    };
  }

  const queryParams = stringify(
    {
      page,
      pagination: true,
      limit: 9,
      where: queryCondition,
    },
    { addQueryPrefix: true }
  );

  const blogRequest = await fetch(`/api/blogs${queryParams}`);

  if (blogRequest.ok) {
    const resData = (await blogRequest.json()) as PaginatedDocs<Blog>;
    const formattedData: BlogData[] = resData.docs.map((item) => {
      return {
        slug: item.slug,
        title: item.title,
        description: sanitizeBlogContentIntoStringPreview(item.content),
        img: typeof item.img !== "number" ? { url: item?.img?.url ?? "", alt: item.img.alt } : undefined,
        posted_at: formatDate(item.createdAt),
      };
    });

    return {
      ...resData,
      formattedData,
    };
  } else {
    return null;
  }
}

export async function fetchRecentBlogREST({ currentBlogId }: FetchRecentBlogParams) {
  const queryCondition: Where = {
    _status: { equals: "published" },
    id: {
      not_equals: currentBlogId,
    },
  };

  const queryParams = stringify(
    {
      pagination: true,
      limit: 2,
      where: queryCondition,
    },
    { addQueryPrefix: true }
  );

  const blogRequest = await fetch(`/api/blogs${queryParams}`);

  if (blogRequest.ok) {
    const resData = (await blogRequest.json()) as PaginatedDocs<Blog>;
    const formattedData: BlogData[] = resData.docs.map((item) => {
      return {
        slug: item.slug,
        title: item.title,
        description: sanitizeBlogContentIntoStringPreview(item.content),
        img: typeof item.img !== "number" ? { url: item?.img?.url ?? "", alt: item.img.alt } : undefined,
        posted_at: formatDate(item.createdAt),
      };
    });

    return {
      ...resData,
      formattedData,
    };
  } else {
    return null;
  }
}
