import { useQuery } from "@pinia/colada";
import type { AxiosResponse } from "axios";
import { computed } from "vue";
import { useApi } from "~/composables/useApi";
import type { ProjectsResponse } from "~/types/projects";
import type { ProjectDetails } from "~/types/singleProject";

export function useCategorysQuery(page: number) {
  const { get } = useApi();
  const { locale } = useI18n();
  return useQuery({
    staleTime: 1000 * 60 * 60,
    key: computed(() => ["projects", page, locale.value]),
    query: async () => {
      try {
        const response = await get<ProjectsResponse>(`projects`, {
          params: { page },
        });
        return response.data;
      } catch (error: any) {
        console.error(error.message);
      }
    },
  });
}
export function useCategoryQuery(serviceId: string, page: number) {
  const { get } = useApi();
  const { locale } = useI18n();
  return useQuery({
    staleTime: 1000 * 60 * 60,
    key: computed(() => ["projects", serviceId, page, locale.value]),
    query: async () => {
      try {
        const response = await get<ProjectsResponse>(`projects`, {
          params: {
            service_id: serviceId,
            page,
          },
        });
        return response.data;
      } catch (error: any) {
        console.error(error.message);
      }
    },
  });
}

export function useProjectDetailsQuery(slug: string) {
  const { get } = useApi();
  const { locale } = useI18n();
  return useQuery({
    staleTime: 1000 * 60 * 60,
    key: computed(() => ["project", slug, locale.value]),
    query: async () => {
      try {
        const response = (await get(`projects/${slug}`)) as AxiosResponse;
        return response.data.data as ProjectDetails;
      } catch (error: any) {
        throw createError({
          statusCode: error?.response?.status || 404,
          statusMessage: "Project Not Found",
        });
      }
    },
  });
}
