import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:niogu_ecommerce_v1/core/constant/app_config.dart';
import 'package:niogu_ecommerce_v1/core/constant/app_temp.dart';
import 'package:niogu_ecommerce_v1/core/system/system_secure.dart';
import 'package:niogu_ecommerce_v1/core/utils/log_message.dart';

class DioClient {
  late final Dio _dio;

  DioClient() {
    _dio = Dio(
      BaseOptions(
        baseUrl: AppConfig.BASE_URL,
        connectTimeout: const Duration(seconds: 15),
        receiveTimeout: const Duration(seconds: 15),
        responseType: ResponseType.json,
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'X-Business-Code': AppTemp.BUSINESS_CODE,
        },
      ),
    );

    _dio.interceptors.add(
      LogInterceptor(requestBody: kDebugMode, responseBody: kDebugMode),
    );

    _dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) async {
          final token = await SystemSecure.getAccessToken();

          if (token != null) {
            options.headers['Authorization'] = 'Bearer $token';
          }

          return handler.next(options);
        },
        onError: (DioException e, handler) {
          if (e.response?.statusCode == 401) {
            LogMessage.log.e("Sesi berakhir, silakan login ulang.");
          }
          return handler.next(e);
        },
      ),
    );
  }

  Dio get instance => _dio;
}
