import 'package:rasadyar_auth/data/common/dio_error_handler.dart';
import 'package:rasadyar_auth/data/models/response/auth/auth_response_model.dart';
import 'package:rasadyar_auth/data/repositories/auth_repository_imp.dart';
import 'package:rasadyar_auth/data/services/token_storage_service.dart';
import 'package:rasadyar_core/core.dart';

import '../common/dio_manager.dart';

GetIt diAuth = GetIt.instance;

Future<void> setupAuthDI() async {
  diAuth.registerLazySingleton(() => DioRemoteManager());
  diAuth.registerLazySingleton<AppInterceptor>(
    () => AppInterceptor(
      refreshTokenCallback: () async {
        var tokenService = Get.find<TokenStorageService>();
        final authRepo = diAuth.get<AuthRepositoryImpl>();

        final refreshToken = tokenService.refreshToken.value;
        if (refreshToken == null) return null;

        final result = await authRepo.loginWithRefreshToken(authRequest: {"refresh_token": refreshToken});

        if (result is AuthResponseModel) {
          await tokenService.saveAccessToken(result.access!);
          return result.access;
        }
        return null;
      },
    ),
  );

  diAuth.registerLazySingleton<DioRemote>(() => DioRemote(interceptors: [diAuth.get<AppInterceptor>()]));

  final dioRemote = diAuth.get<DioRemote>();
  await dioRemote.init();
  diAuth.registerSingleton<AuthRepositoryImpl>(AuthRepositoryImpl(dioRemote));
  diAuth.registerLazySingleton<DioErrorHandler>(() => DioErrorHandler());
}

Future<void> newSetupAuthDI(String newUrl) async {
  diAuth.registerLazySingleton<DioRemote>(
    () => DioRemote(baseUrl: newUrl, interceptors: [diAuth.get<AppInterceptor>()]),
    instanceName: 'newRemote',
  );
  final dioRemote = diAuth.get<DioRemote>(instanceName: 'newRemote');
  await dioRemote.init();
  diAuth.registerSingleton<AuthRepositoryImpl>(AuthRepositoryImpl(dioRemote), instanceName: 'newUrl');
}
