import 'package:get_it/get_it.dart';
import 'package:dio/dio.dart';
import 'package:kmobile/api/services/beneficiary_service.dart';
import 'package:kmobile/api/services/payment_service.dart';
import 'package:kmobile/api/services/user_service.dart';
import 'package:kmobile/data/repositories/transaction_repository.dart';
import '../api/services/auth_service.dart';
import '../api/interceptors/auth_interceptor.dart';
import '../data/repositories/auth_repository.dart';
import '../features/auth/controllers/auth_cubit.dart';
import '../security/secure_storage.dart';

final getIt = GetIt.instance;

Future<void> setupDependencies() async {
  // Register Dio client
  getIt.registerSingleton<Dio>(_createDioClient());

  // Register secure storage
  getIt.registerSingleton<SecureStorage>(SecureStorage());

  // Register user service if needed
  getIt.registerSingleton<UserService>(UserService(getIt<Dio>()));

  // Register services
  getIt.registerSingleton<AuthService>(AuthService(getIt<Dio>()));

  // Register repositories
  getIt.registerSingleton<AuthRepository>(
    AuthRepository(
        getIt<AuthService>(), getIt<UserService>(), getIt<SecureStorage>()),
  );
  getIt.registerSingleton<TransactionRepository>(
      TransactionRepositoryImpl(getIt<Dio>()));

  getIt.registerSingleton<PaymentService>(PaymentService(getIt<Dio>()));
  getIt.registerSingleton<BeneficiaryService>(BeneficiaryService(getIt<Dio>()));

  // Add auth interceptor after repository is available
  getIt<Dio>().interceptors.add(
        AuthInterceptor(getIt<AuthRepository>(), getIt<Dio>()),
      );

  // Register controllers/cubits
  getIt.registerFactory<AuthCubit>(
      () => AuthCubit(getIt<AuthRepository>(), getIt<UserService>()));
}

Dio _createDioClient() {
  final dio = Dio(
    BaseOptions(
      baseUrl:
          'http://lb-test-mobile-banking-app-192209417.ap-south-1.elb.amazonaws.com:8080',
      connectTimeout: const Duration(seconds: 5),
      receiveTimeout: const Duration(seconds: 3),
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
    ),
  );

  // Add logging interceptor for development
  dio.interceptors.add(LogInterceptor(
    request: true,
    requestHeader: true,
    requestBody: true,
    responseHeader: true,
    responseBody: true,
    error: true,
  ));

  return dio;
}
