import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { queryKeys } from "./keys";
import { facilityService } from "@/services/facility.service";
import type { PaginationParams } from "@/types";
import type { FacilityCreateRequest, AssetCreateRequest } from "@/types/facility";

export function useFacilities(params?: PaginationParams) {
  return useQuery({
    queryKey: queryKeys.facilities.list(params),
    queryFn: () => facilityService.listFacilities(params),
  });
}

export function useCreateFacility() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: FacilityCreateRequest) => facilityService.createFacility(data),
    onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.facilities.all }),
  });
}

export function useUpdateFacility() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ id, data }: { id: number; data: Partial<FacilityCreateRequest> }) =>
      facilityService.updateFacility(id, data),
    onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.facilities.all }),
  });
}

export function useDeleteFacility() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: number) => facilityService.deleteFacility(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.facilities.all }),
  });
}

export function useAssets(params?: PaginationParams) {
  return useQuery({
    queryKey: queryKeys.assets.list(params),
    queryFn: () => facilityService.listAssets(params),
  });
}

export function useCreateAsset() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: AssetCreateRequest) => facilityService.createAsset(data),
    onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.assets.all }),
  });
}

export function useDeleteAsset() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: number) => facilityService.deleteAsset(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.assets.all }),
  });
}
