import { useQuery } from "@tanstack/react-query";
import {
  getPersonalDetailsMasters,
  getCasteMasters,
  getSubCasteMasters,
  getCityMasters,
  getStarMasters,
} from "../api/masters.api";

/** Personal details masters (gender, marital status, religion, gothram, raasi, state, etc.) */
export const usePersonalDetailsMasters = () =>
  useQuery({
    queryKey: ["personal-details-masters"],
    queryFn: getPersonalDetailsMasters,
    staleTime: 1000 * 60 * 60, // 1 hour
  });

/** Caste depends on religion */
export const useCasteMasters = (religion_id) =>
  useQuery({
    queryKey: ["caste-masters", religion_id],
    queryFn: () => getCasteMasters(religion_id),
    enabled: !!religion_id, // 🚫 prevents unwanted call
  });

/** Sub caste depends on caste */
export const useSubCasteMasters = (caste_id) =>
  useQuery({
    queryKey: ["sub-caste-masters", caste_id],
    queryFn: async () => {
      if (Array.isArray(caste_id)) {
        const results = await Promise.all(
          caste_id.map((id) => getSubCasteMasters(id))
        );
        return results;
      }
      return getSubCasteMasters(caste_id);
    },
    enabled: Array.isArray(caste_id) ? caste_id.length > 0 : !!caste_id,
  });

/** City depends on state */
export const useCityMasters = (state_id) =>
  useQuery({
    queryKey: ["city-masters", state_id],
    queryFn: () => getCityMasters(state_id),
    enabled: Array.isArray(state_id) ? state_id.length > 0 : !!state_id,
  });

/** Star depends on raasi */
export const useStarMasters = (raasi_id) =>
  useQuery({
    queryKey: ["star-masters", raasi_id],
    queryFn: () => getStarMasters(raasi_id),
    enabled: !!raasi_id,
  });
