import payloadConfig from "@/payload.config";
import { formatDate } from "@/utils/datetime";
import { getPayload } from "payload";

export const fetchPageBySlug = async ({ slug }: { slug: string | undefined }) => {
  const payload = await getPayload({ config: payloadConfig });

  const result = await payload.find({
    collection: "pages",
    // draft,
    limit: 1,
    pagination: false,
    // overrideAccess: draft,
    where: {
      _status: { equals: "published" },
      slug: {
        equals: slug,
      },
    },
  });

  if (!result.docs?.[0]) {
    return null;
  }

  const data = result.docs[0];

  const heroImgUrl = typeof data.hero_img !== "number" ? (data?.hero_img?.url ?? "") : "";
  const heroImgAlt = typeof data.hero_img !== "number" ? (data?.hero_img?.alt ?? "") : "";

  return {
    data: data,
    createdAt: formatDate(data.createdAt),
    updatedAt: formatDate(data.updatedAt),
    heroImg: {
      url: heroImgUrl,
      alt: heroImgAlt,
    },
  };
};
