import 'package:dio/dio.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:get_it/get_it.dart';
import '../api/api_client.dart';
import '../api/i_api_client.dart';
import '../api/mock_api_client.dart';
import '../storage/token_storage.dart';
import '../config/env.dart';
import '../../features/auth/data/auth_api.dart';
import '../../features/auth/data/auth_repository.dart';
import '../../features/auth/data/auth_repository_impl.dart';
import '../../features/auth/presentation/bloc/auth_bloc.dart';
import '../../features/calendar/ui/calendar_state_manager.dart';

final sl = GetIt.instance;

Future<void> configureDependencies() async {
  if (sl.isRegistered<IApiClient>()) {
    await sl.reset();
  }

  final IApiClient apiClient;
  final SecureTokenStorage tokenStorage;

  if (Env.isMockApi) {
    apiClient = MockApiClient();
    tokenStorage = SecureTokenStorage(const FlutterSecureStorage());
  } else {
    final dio = Dio(BaseOptions(baseUrl: Env.apiUrl));
    tokenStorage = SecureTokenStorage(const FlutterSecureStorage());
    apiClient = ApiClient(
      baseUrl: Env.apiUrl,
      tokenStorage: tokenStorage,
      dio: dio,
    );
  }

  sl.registerSingleton<IApiClient>(apiClient);

  final authApi = AuthApi(apiClient);
  sl.registerSingleton<AuthApi>(authApi);

  final authRepository = AuthRepositoryImpl(
    api: authApi,
    tokenStorage: tokenStorage,
  );
  sl.registerSingleton<AuthRepository>(authRepository);

  if (!Env.isMockApi) {
    (apiClient as ApiClient).setRefreshCallback((token) async {
      try {
        await authRepository.refreshSession(token);
        return true;
      } catch (_) {
        return false;
      }
    });
  }

  sl.registerSingleton<AuthBloc>(AuthBloc(authRepository));
  sl.registerSingleton<CalendarStateManager>(CalendarStateManager());
}
