import { useMutation, useQuery } from "@tanstack/react-query";
import {
  getOrganizations,
  OrgQueryParams,
  getOrganizationById,
} from "@/shared/services/organizationsService";

import { OrganizationDto } from "@/shared/dto/organization/organizationDto";

interface Unit {
  id: string;
  name: string;
  departments: any[];
  isExpanded?: boolean;
}

export interface Organization {
  id: string;
  name: string;
  units: Unit[];
  isExpanded?: boolean;
}

export const useOrganizations = (params?: OrgQueryParams) => {
  const {
    data: organizationsResponse,
    isLoading,
    isError,
    refetch,
  } = useQuery({
    queryKey: ["organizations", params],
    queryFn: async () => {
      const { data } = await getOrganizations(params);
      return {
        count: data.count as number,
        items: data.items as OrganizationDto[],
      };
    },
    staleTime: 5 * 60 * 1000,
    retry: false,
  });

  const { mutate: getOrganization, isPending: isFetchingOrganization } =
    useMutation({
      mutationFn: async (id: string) => {
        const { data } = await getOrganizationById(id);
        return data;
      },
      onSuccess: (data) => {
        return data;
      },
    });

  return {
    organizationsResponse,
    isLoading,
    isError,
    refetch,
    getOrganizationByDetails: getOrganization,
  };
};
