import { useQuery } from "@pinia/colada";
import { useApi } from "~/composables/useApi";
import { computed } from "vue";
import type { AxiosResponse } from "axios";
import type { BlogsResponse } from "~/types/blogCard";

export function useBlogsQuery(page: Ref<number> | ComputedRef<number>) {
  const { get } = useApi();
  const { locale } = useI18n();

  return useQuery({
    staleTime: 1000 * 60 * 60,
    key: computed(() => ["blogs", locale.value, page.value]),
    query: async () => {
      try {
        const response = (await get("blogs", {
          params: { page: page.value },
        })) as AxiosResponse<BlogsResponse>;
        return response.data;
      } catch (error: any) {
        console.error(error.message);
        throw error;
      }
    },
  });
}
export function useBlogQuery(slug: string) {
  const { get } = useApi();
  const { locale } = useI18n();

  return useQuery({
    staleTime: 1000 * 60 * 60,
    key: computed(() => ["blog", slug, locale.value]),

    query: async () => {
      try {
        const response = (await get(`blogs/${slug}`)) as AxiosResponse;
        return {
          blog: response.data.data,
          relatedBlogs: response.data.data.related_blogs,
        };
      } catch (error: any) {
        throw createError({
          statusCode: error?.response?.status || 404,
          statusMessage: "Blog Not Found",
        });
      }
    },
  });
}
