import { getClient } from "@/lib/apolloClient";
import { BLOGS_AND_CATEGORIES_QUERY } from "./blogQuery";

/* ---------- TYPES ---------- */

type BlogPost = {
  id: string;
  slug: string;
  title: string;
};

type BlogCategory = {
  id: string;
  name: string;
  slug: string;
};

type BlogsAndCategoriesQueryResult = {
  posts: {
    nodes: BlogPost[];
    pageInfo: {
      hasNextPage: boolean;
      endCursor: string | null;
    };
  };
  categories: {
    nodes: BlogCategory[];
  };
};

/* ---------- FUNCTION ---------- */

export async function getAllBlogsAndCategories(category = "") {
  const client = getClient();

  const allPosts: BlogPost[] = [];
  const categories: BlogCategory[] = [];

  let hasNextPage = true;
  let after: string | null = null;

  while (hasNextPage) {
    const data: BlogsAndCategoriesQueryResult =
      (await client.query<BlogsAndCategoriesQueryResult>({
        query: BLOGS_AND_CATEGORIES_QUERY,
        variables: { category, after },
      })).data!; // ✅ explicit type + non-null assertion

    allPosts.push(...data.posts.nodes);

    if (categories.length === 0) {
      categories.push(...data.categories.nodes);
    }

    hasNextPage = data.posts.pageInfo.hasNextPage;
    after = data.posts.pageInfo.endCursor;
  }

  return {
    posts: allPosts,
    categories,
  };
}
