import { useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import { getProfile } from "@/lib/services/profile.service";
import { EducationApiItem, MappedEducation } from "../types/education.types";
import { mapEducations } from "../utils/education.utils";

interface UseEducationDataReturn {
  mappedEducations: MappedEducation[];
  isLoading: boolean;
  isError: boolean;
}

/**
 * Owns the profile READ query for the education section.
 * Returns memoized mapped educations for CustomTextbox options.
 */
export function useEducationData(): UseEducationDataReturn {
  const profileQuery = useQuery({
    queryKey: ["profile"],
    queryFn: getProfile,
    staleTime: 5 * 60 * 1000,
  });

  const mappedEducations = useMemo<MappedEducation[]>(
    () =>
      mapEducations(
        profileQuery.data?.data?.educations as EducationApiItem[] | undefined,
      ),
    [profileQuery.data],
  );

  return {
    mappedEducations,
    isLoading: profileQuery.isLoading,
    isError: profileQuery.isError,
  };
}
