import 'package:chucker_flutter/chucker_flutter.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:frontend_eccp_mobile/app/core/config/app_environment.dart';
import 'package:frontend_eccp_mobile/app/core/config/app_flavor.dart';
import 'package:frontend_eccp_mobile/app/core/network/interceptors/auth_interceptor.dart';
import 'package:frontend_eccp_mobile/app/core/network/interceptors/error_interceptor.dart';
import 'package:frontend_eccp_mobile/app/core/network/interceptors/logging_interceptor.dart';
import 'package:frontend_eccp_mobile/app/core/network/interceptors/retry_interceptor.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';

class DioClient {
  DioClient._();

  static final Dio _dio = Dio(
    BaseOptions(
      baseUrl: AppEnvironment.baseUrl,
      validateStatus: (status) =>
          status != null && status >= 200 && status < 300,
      connectTimeout: const Duration(
        seconds: AppEnvironment.connectTimeoutSeconds,
      ),
      receiveTimeout: const Duration(
        seconds: AppEnvironment.receiveTimeoutSeconds,
      ),
    ),
  );

  static Dio getInstance() {
    _dio.interceptors.clear();

    _dio.interceptors.add(AuthInterceptor());
    _dio.interceptors.add(buildRetryInterceptor(_dio));
    _dio.interceptors.add(LoggingInterceptor());
    _dio.interceptors.add(ErrorInterceptor(_dio));
    _dio.interceptors.add(
      PrettyDioLogger(
        requestHeader: true,
        requestBody: true,
      ),
    );

    if (!kReleaseMode && Flavor.isDev) {
      _dio.interceptors.add(ChuckerDioInterceptor());
    }

    return _dio;
  }
}
