import { Property } from "@/payload-types";
import { CardPropertyData } from "@/schema/property";
import { formatDate } from "@/utils/datetime";
import { PaginatedDocs, Where } from "payload";
import { stringify } from "qs-esm";

export async function fetchLatestPropertyREST() {
  const limitPerPage = 6;

  const queryCondition: Where = {
    _status: { equals: "published" },
  };

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

  const req = await fetch(`/api/properties${queryParams}`);
  if (req.ok) {
    const resData = (await req.json()) as PaginatedDocs<Property>;
    const formattedData: CardPropertyData[] = resData.docs.map((item) => {
      return {
        slug: item.slug ?? "",
        title: item.name,
        price: item.base_price,
        area: item.aboutGroup.area,
        propertyType: item.property_type,
        bathrooms_count: item.aboutGroup.bathrooms_count,
        bedrooms_count: item.aboutGroup.bedrooms_count,
        images: item.images.map((img) =>
          typeof img !== "number" ? { url: img?.url ?? "", alt: img.alt } : { url: "", alt: "" }
        ),
        posted_at: formatDate(item.createdAt),
      };
    });

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