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 '../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<ApiClient>()) {
    await sl.reset();
  }

  final dio = Dio(BaseOptions(baseUrl: Env.apiUrl));
  final secureStorage = const FlutterSecureStorage();
  final tokenStorage = SecureTokenStorage(secureStorage);

  final apiClient = ApiClient(
    baseUrl: Env.apiUrl,
    tokenStorage: tokenStorage,
    dio: dio,
  );
  sl.registerSingleton<ApiClient>(apiClient);

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

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

  apiClient.setRefreshCallback((token) async {
    try {
      await authRepository.refreshSession(token);
      return true;
    } catch (_) {
      return false;
    }
  });

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

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