import { useQuery, UseQueryOptions } from '@tanstack/react-query';
import { useInject } from '@/lib/di/hooks/useInject';
import { DRIVER_SERVICE_TOKEN } from '@/lib/di/tokens';
import { enhanceQueryResult } from '@/lib/di/hooks/useReactQueryWithApiError';
import { ApiError } from '@/lib/api/base/ApiError';
import type { GetDriverOutputDTO } from '@/lib/types/generated/GetDriverOutputDTO';

export function useFindDriverById(
  driverId: string,
  options?: Omit<UseQueryOptions<GetDriverOutputDTO | null, ApiError>, 'queryKey' | 'queryFn'>
) {
  const driverService = useInject(DRIVER_SERVICE_TOKEN);

  const queryResult = useQuery({
    queryKey: ['driver', driverId],
    queryFn: async () => {
      const result = await driverService.findById(driverId);
      if (result.isErr()) {
        const error = result.getError();
        throw new ApiError(error.message, 'SERVER_ERROR', { timestamp: new Date().toISOString() });
      }
      return result.unwrap();
    },
    enabled: !!driverId,
    ...options,
  });

  return enhanceQueryResult(queryResult);
}
