import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { packageService } from '../services/packageService';
import {
  Package,
  CreatePackageRequest,
  PackageFilter,
  PaginatedResponse
} from '../types';

export const usePackages = (
  page: number = 1,
  pageSize: number = 10,
  filter?: PackageFilter
) => {
  return useQuery<PaginatedResponse<Package>>({
    queryKey: ['packages', page, pageSize, filter],
    queryFn: () => packageService.getPackages(page, pageSize, filter),
    keepPreviousData: true,
  });
};

export const usePackage = (id: number) => {
  return useQuery({
    queryKey: ['package', id],
    queryFn: () => packageService.getPackage(id),
    enabled: !!id,
  });
};

export const useCreatePackage = () => {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: (request: CreatePackageRequest) => packageService.createPackage(request),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['packages'] });
    },
  });
};

export const useUpdatePackage = () => {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: ({ id, request }: { id: number; request: Partial<CreatePackageRequest> }) => 
      packageService.updatePackage(id, request),
    onSuccess: (_, { id }) => {
      queryClient.invalidateQueries({ queryKey: ['package', id] });
      queryClient.invalidateQueries({ queryKey: ['packages'] });
    },
  });
};

export const useDeletePackage = () => {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: (id: number) => packageService.deletePackage(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['packages'] });
    },
  });
};

export const usePublishPackage = () => {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: ({ packageId, buildId }: { packageId: number; buildId: number }) => 
      packageService.publishPackage(packageId, buildId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['packages'] });
      queryClient.invalidateQueries({ queryKey: ['publications'] });
    },
  });
};