import { useQuery } from "@pinia/colada";
import { useApi } from "~/composables/useApi";
import type { AxiosResponse } from "axios";
import type { Job } from "~/types/Job";

export function useJobsQuery() {
  const { get } = useApi();
  const { locale } = useI18n();

  return useQuery({
    staleTime: 1000 * 60 * 60,
    key: computed(() => ["jobs", locale.value]),
    query: async () => {
      try {
        const response = (await get("jobs")) as AxiosResponse;
        return response.data.data as Job[];
      } catch (error: any) {
        console.error(error.message);
      }
    },
  });
}

export function useJobQuery(slug: string) {
  const { get } = useApi();
  const { locale } = useI18n();

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