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 { DriverDTO } from '@/lib/types/generated/DriverDTO';
import { useAuth } from '@/components/auth/AuthContext';

export function useCurrentDriver(
  options?: Omit<UseQueryOptions<DriverDTO | null, ApiError>, 'queryKey' | 'queryFn'>
) {
  const driverService = useInject(DRIVER_SERVICE_TOKEN);
  const { session } = useAuth();

  const queryResult = useQuery({
    queryKey: ['currentDriver'],
    queryFn: async () => {
      const result = await driverService.getCurrentDriver();
      if (result.isErr()) {
        throw result.getError();
      }
      return result.unwrap();
    },
    enabled: !!session,
    retry: false,
    refetchOnWindowFocus: false,
    ...options,
  });

  return enhanceQueryResult(queryResult);
}
