import { useMutation, UseMutationOptions } from '@tanstack/react-query';
import { useInject } from '@/lib/di/hooks/useInject';
import { AUTH_SERVICE_TOKEN } from '@/lib/di/tokens';
import { ApiError } from '@/lib/api/base/ApiError';
import { SessionViewModel } from '@/lib/view-models/SessionViewModel';
import type { LoginParamsDTO } from '@/lib/types/generated/LoginParamsDTO';

export function useLogin(
  options?: Omit<UseMutationOptions<SessionViewModel, ApiError, LoginParamsDTO>, 'mutationFn'>
) {
  const authService = useInject(AUTH_SERVICE_TOKEN);

  return useMutation<SessionViewModel, ApiError, LoginParamsDTO>({
    mutationFn: async (params) => {
      const result = await authService.login(params);
      if (result.isErr()) {
        throw result.getError();
      }
      return result.unwrap();
    },
    ...options,
  });
}