import 'package:dio/dio.dart';
import 'package:hamlemuhcrm/core/constants/url_services_constant.dart';

import '../../../features/auth/login/view/login_view.dart';
import '../../enum/user_enum.dart';
import '../../route/page_route.dart';
import '../application/my_app.dart';
import '../cache/cache_manager.dart';

final class NetworkManager {
  static NetworkManager? _instance;
  static NetworkManager get instance {
    _instance ??= NetworkManager._init();
    return _instance!;
  }

  late final Dio dio;
  NetworkManager._init() {
    dio = Dio(BaseOptions(baseUrl: URLAPIService.baseURL));
    dio.interceptors.add(InterceptorsWrapper(
      onError: (e, handler) async {
        if (e.response?.statusCode == 401) {
          // 401 unauthorized durumlarında login sayfasına yönlendiricez ve eski verileri cache üzerinden temizlicez.
          cleanCacheData();
          navigatorKey.currentState
              ?.pushReplacement(CustomPageRoute(child: const LoginView()));
        }
        //
      },
    ));
  }

  void cleanCacheData() {
    CacheManager.instance.removeValue(UserEnum.loginid.toName);
    CacheManager.instance.removeValue(UserEnum.token.toName);
    CacheManager.instance.removeValue(UserEnum.fcmtoken.toName);
    CacheManager.instance.removeValue(UserEnum.userfirmid.toName);
  }
}
