import { directus } from "@/lib/directus";
import { ItemsQuery, Post } from "@/types";
import { readItem, readItems } from "@directus/sdk";

// Construct base URL for assets from environment variable
const assetsUrl = `${process.env.DIRECTUS_API_ENDPOINT}/assets/`;

function getFullImageUrl(imageId: string | null | undefined): string | null {
  if (!imageId || !assetsUrl) {
    return null;
  }
  return `${assetsUrl}${imageId}`;
}

// Function to fetch all published posts
export async function getPosts(): Promise<Post[]> {
  try {
    const postsData = await directus.request(
      readItems("posts", {
        fields: [
          "slug",
          "title",
          "excerpt",
          "featured_image",
          "date_created",
          "content",
        ],
        filter: {
          status: { _eq: "published" },
        },
        sort: ["-date_created"],
      })
    );

    const posts = postsData.map((post) => ({
      ...post,
      featured_image: getFullImageUrl(post.featured_image),
    })) as Post[];

    return posts;
  } catch (error) {
    console.error("Error fetching posts:", error);
    return [];
  }
}

// Function to fetch a single post by slug
export async function getPostBySlug(
  slug: string,
  options?: ItemsQuery
): Promise<Post | null> {
  try {
    const postData = await directus.request(readItem("posts", slug, options));

    // Map data to include full image URL
    const post = {
      ...postData,
      featured_image: getFullImageUrl(postData.featured_image),
    } as Post; // Adjust cast if needed

    return post;
  } catch (error) {
    console.error(`Error fetching post with slug ${slug}:`, error);
    return null;
  }
}
