import { useQuery, UseQueryOptions } from '@tanstack/react-query';
import { useInject } from '@/lib/di/hooks/useInject';
import { SESSION_SERVICE_TOKEN } from '@/lib/di/tokens';
import { enhanceQueryResult } from '@/lib/di/hooks/useReactQueryWithApiError';
import { ApiError } from '@/lib/api/base/ApiError';
import { SessionViewModel } from '@/lib/view-models/SessionViewModel';

export function useCurrentSession(
  options?: Omit<UseQueryOptions<SessionViewModel | null, ApiError>, 'queryKey' | 'queryFn'> & { initialData?: SessionViewModel | null }
) {
  const sessionService = useInject(SESSION_SERVICE_TOKEN);

  const queryResult = useQuery({
    queryKey: ['currentSession'],
    queryFn: async () => {
      const result = await sessionService.getSession();
      if (result.isErr()) {
        const error = result.getError();
        throw new ApiError(error.message, 'SERVER_ERROR', { timestamp: new Date().toISOString() });
      }
      const session = result.unwrap();
      return session ? new SessionViewModel(session.user as any) : null;
    },
    initialData: options?.initialData,
    retry: false,
    refetchOnWindowFocus: false,
    ...options,
  });

  return enhanceQueryResult(queryResult);
}