import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { ApiResponse } from "@/types/api-response";
import { adminPermissionsService } from "./service";
import { PermissionResponseDto, CreatePermissionDto } from "./types";

export const AdminPermissionsQueryKeys = {
  all: ["admin-permissions"] as const,
  list: () => [...AdminPermissionsQueryKeys.all, "list"] as const,
};

export function useGetAllPermissions() {
  const queryKey = AdminPermissionsQueryKeys.list();

  const { data, ...rest } = useQuery<ApiResponse<PermissionResponseDto[]>>({
    queryKey: queryKey,
    queryFn: adminPermissionsService.getAll,
  });

  return { data: data?.data, ...rest };
}

export function useCreatePermission() {
  const queryClient = useQueryClient();

  const { data, ...rest } = useMutation<
    ApiResponse<PermissionResponseDto>,
    Error,
    CreatePermissionDto
  >({
    mutationFn: (permissionData) =>
      adminPermissionsService.create(permissionData),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: AdminPermissionsQueryKeys.all,
      });
    },
  });

  return { data: data?.data, ...rest };
}
