import '../config/app_config.dart';
import 'interfaces/auth_service.dart';
import 'interfaces/user_service.dart';
import 'interfaces/group_service.dart';
import 'interfaces/notification_service.dart';
import 'api/api_client.dart';
import 'api/auth_api_service.dart';
import 'api/user_api_service.dart';
import 'api/group_api_service.dart';
import 'api/notification_api_service.dart';
import 'mock/mock_auth_service.dart';
import 'mock/mock_user_service.dart';
import 'mock/mock_group_service.dart';
import 'mock/mock_notification_service.dart';

/// Singleton that wires together the correct service implementations
/// based on [AppConfig.debugMode].
class ServiceLocator {
  static final ServiceLocator _instance = ServiceLocator._internal();
  factory ServiceLocator() => _instance;
  ServiceLocator._internal();

  late final AuthService auth;
  late final UserService users;
  late final GroupService groups;
  late final NotificationService notifications;

  ApiClient? _apiClient;

  void initialize() {
    if (AppConfig.debugMode) {
      auth = MockAuthService();
      users = MockUserService();
      groups = MockGroupService();
      notifications = MockNotificationService();
    } else {
      _apiClient = ApiClient(baseUrl: AppConfig.baseUrl);
      auth = AuthApiService(_apiClient!);
      users = UserApiService(_apiClient!);
      groups = GroupApiService(_apiClient!);
      notifications = NotificationApiService(_apiClient!);
    }
  }

  void setToken(String token) => _apiClient?.setToken(token);
  void clearToken() => _apiClient?.clearToken();

  /// Exposed for one-off direct API calls (e.g. notifications).
  ApiClient get apiClient {
    if (_apiClient == null) {
      throw StateError('ApiClient not initialized – running in debug mode?');
    }
    return _apiClient!;
  }
}
