import 'package:rasadyar_core/core.dart';
import 'package:rasadyar_livestock/data/common/dio_exception_handeler.dart';
import 'package:rasadyar_livestock/data/data_source/remote/auth/auth_remote.dart';
import 'package:rasadyar_livestock/data/data_source/remote/auth/auth_remote_imp.dart';
import 'package:rasadyar_livestock/data/data_source/remote/livestock/livestock_remote.dart';
import 'package:rasadyar_livestock/data/data_source/remote/livestock/livestock_remote_imp.dart';
import 'package:rasadyar_livestock/data/repository/auth/auth_repository.dart';
import 'package:rasadyar_livestock/data/repository/auth/auth_repository_imp.dart';
import 'package:rasadyar_livestock/data/repository/livestock/livestock_repository.dart';
import 'package:rasadyar_livestock/data/repository/livestock/livestock_repository_imp.dart';
import 'package:rasadyar_livestock/data/service/live_stock_storage_service.dart';
import 'package:rasadyar_livestock/hive_registrar.g.dart';
import 'package:rasadyar_livestock/presentation/routes/app_pages.dart';

import '../data/data_source/local/tmp/tmp_local_data-source.dart';

GetIt diLiveStock = GetIt.asNewInstance();

Future<void> setupLiveStockDI() async {
  diLiveStock.registerSingleton(DioErrorHandler());

  await IsolatedHive.initFlutter();
  IsolatedHive.registerAdapters();
  final tokenService = Get.find<TokenStorageService>();
  Get.lazyPut(() => LiveStockStorageService());

  if (tokenService.baseurl.value == null) {
    await tokenService.saveBaseUrl(Module.inspection, 'https://api.dam.rasadyar.net/');
  }

  // First register AppInterceptor with lazy callbacks
  diLiveStock.registerLazySingleton<AppInterceptor>(
    () => AppInterceptor(
      refreshTokenCallback: () async {
        // Use lazy access to avoid circular dependency
        final authRepository = diLiveStock.get<AuthRepository>();
        final hasAuthenticated = await authRepository.hasAuthenticated();
        if (hasAuthenticated) {
          final newToken = await authRepository.loginWithRefreshToken(
            authRequest: {'refresh': tokenService.refreshToken.value},
          );
          return newToken?.access;
        }
        return null;
      },
      saveTokenCallback: (String newToken) async {
        //    await tokenService.saveAccessToken(newToken);
      },
      clearTokenCallback: () async {
        await tokenService.deleteModuleTokens(Module.liveStocks);
        Get.offAllNamed(LiveStockRoutes.auth, arguments: Module.liveStocks);
      },
      authArguments: Module.liveStocks,
    ),
  );

  // Register DioRemote with the interceptor
  diLiveStock.registerLazySingleton<DioRemote>(
    () => DioRemote(
      baseUrl: tokenService.baseurl.value,
      // interceptors: diLiveStock.get<AppInterceptor>(),
    ),
  );

  // Initialize DioRemote
  await diLiveStock.get<DioRemote>().init();

  // Now register the data source and repository

  //region Auth
  diLiveStock.registerLazySingleton<AuthRemoteDataSource>(
    () => AuthRemoteDataSourceImp(diLiveStock.get<DioRemote>()),
  );

  diLiveStock.registerLazySingleton<AuthRepository>(
    () => AuthRepositoryImp(authRemote: diLiveStock.get<AuthRemoteDataSource>()),
  );
  //endregion

  //region Livestock
  diLiveStock.registerLazySingleton<LivestockRemoteDataSource>(
    () => LivestockRemoteDataSourceImp(),
  );

  diLiveStock.registerLazySingleton<TmpLocalDataSource>(() => TmpLocalDataSource());

  diLiveStock.registerLazySingleton<LivestockRepository>(
    () => LivestockRepositoryImp(
      livestockRemote: diLiveStock.get<LivestockRemoteDataSource>(),
      tmpLocalDataSource: diLiveStock.get<TmpLocalDataSource>(),
    ),
  );
  //endregion

  diLiveStock.registerLazySingleton<ImagePicker>(() => ImagePicker());
  await diLiveStock.allReady();
}

Future<void> removeLiveStockDI() async {
  eLog("removeLiveStockDI");
  await diLiveStock.resetScope();
}
