import { getClient } from "@/lib/apolloClient";
import { gql } from "@apollo/client";

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

type PostCategoryResponse = {
  post: {
    categories: {
      nodes: Category[];
    };
  } | null;
};

export async function getCategoryForPost(slug: string) {
  try {
    const { data } = await getClient().query<PostCategoryResponse>({
      query: gql`
        query GetPostCategory($slug: ID!) {
          post(id: $slug, idType: SLUG) {
            categories {
              nodes {
                id
                name
                slug
              }
            }
          }
        }
      `,
      variables: { slug },
    });

    return data?.post?.categories?.nodes?.[0] || null;
  } catch (err) {
    return null;
  }
}
