import 'package:cheminova/services/secure__storage_service.dart';
import 'package:dio/dio.dart';
import 'package:cheminova/services/api_urls.dart';
import 'package:flutter/material.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';

// ApiClient class for making HTTP requests using Dio
class ApiClient {
  final Dio _dio; // Instance of Dio for making HTTP requests
  final SecureStorageService _storageService = SecureStorageService(); // Service for secure storage of tokens

  // Constructor for ApiClient
  ApiClient({String? baseUrl})
      : _dio = Dio(BaseOptions(
      baseUrl: baseUrl ?? ApiUrls.baseUrl, // Set base URL for API
      connectTimeout: const Duration(seconds: 120), // Timeout for connection
      receiveTimeout: const Duration(seconds: 120))) { // Timeout for receiving data

    // Adding interceptors for logging requests and responses
    _dio.interceptors
        .add(LogInterceptor(responseBody: true, requestBody: true)); // Log requests and responses
    _dio.interceptors.add(PrettyDioLogger()); // Pretty logging for requests and responses

    // Adding an interceptor for request handling
    _dio.interceptors
        .add(InterceptorsWrapper(onRequest: (options, handler) async {
      // Retrieve access token from secure storage
      String? token = await _storageService.read(key: 'access_token');
      if (token != null) {
        debugPrint('Token start ------------> $token <------------ Token end'); // Debug log for token
        options.headers['Authorization'] = 'Bearer $token'; // Add token to request headers
      }
      return handler.next(options); // Proceed to the next interceptor or request
    }, onResponse: (response, handler) {
      return handler.next(response); // Proceed to the next interceptor or response
    }, onError: (DioException e, handler) {
      return handler.next(e); // Handle errors and proceed
    }));
  }

  // Method for making GET requests
  Future<dynamic> get(String path, {Map<String, dynamic>? queryParameters}) {
    return _dio.get(path, queryParameters: queryParameters); // Send GET request
  }

  // Method for making POST requests
  Future<Response> post(String path, {dynamic data}) {
    return _dio.post(path, data: data); // Send POST request
  }

  // Method for making PUT requests
  Future<Response> put(String path, {Map<String, dynamic>? data}) {
    return _dio.put(path, data: data); // Send PUT request
  }

  // Method for making DELETE requests
  Future<Response> delete(String path, {Map<String, dynamic>? data}) {
    return _dio.delete(path, data: data); // Send DELETE request
  }
}
