import { useQuery } from "@tanstack/react-query";
import recordAxiosInstance from "@/shared/services/recordAxiosInstance";

export interface PositionPrefixDto {
  id: string;
  name: {
    am: string;
    en: string;
  };
  positionId: string;
  recordTypeKey: string;
  unitId: string;
  createdAt: string;
  updatedAt: string;
}

const fetchPositionPrefixes = async (
  unitId: string,
  recordTypeKey: string = "external",
  positionId?: string,
): Promise<PositionPrefixDto[]> => {
  try {
    const params = new URLSearchParams();
    if (positionId) {
      params.append("positionId", positionId);
    }
    const queryString = params.toString();
    const url = `/record-prefixes/list/by-position/${unitId}/${recordTypeKey}${queryString ? `?${queryString}` : ""}`;
    const { data } = await recordAxiosInstance.get(url);
    return data?.items || [];
  } catch (error: any) {
    console.error("Failed to fetch position prefixes:", error);
    return [];
  }
};

export const usePositionPrefixes = (
  unitId: string,
  recordTypeKey: string = "external",
  positionId?: string,
) => {
  return useQuery({
    queryKey: ["positionPrefixes", unitId, recordTypeKey, positionId],
    queryFn: () => fetchPositionPrefixes(unitId, recordTypeKey, positionId),
    enabled: !!unitId,
    staleTime: 5 * 60 * 1000, // 5 minutes
  });
};
