import 'package:dio/dio.dart';
import 'hmac_interceptor.dart';
import '../storage/secure_storage.dart';

class DioClient {
  static const String baseUrl = 'https://musadaq.intaleqapp.com/api/v1/'; // Update with actual URL
  late final Dio dio;

  DioClient() {
    dio = Dio(
      BaseOptions(
        baseUrl: baseUrl,
        connectTimeout: const Duration(seconds: 15),
        receiveTimeout: const Duration(seconds: 15),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
      ),
    );

    // Add Interceptors
    dio.interceptors.add(HmacInterceptor(SecureStorage()));
    
    // Custom Logging Interceptor as requested
    dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) {
        print('--- API REQUEST ---');
        print('URL: ${options.method} ${options.uri}');
        print('Payload: ${options.data}');
        return handler.next(options);
      },
      onResponse: (response, handler) {
        print('--- API RESPONSE ---');
        print('URL: ${response.requestOptions.method} ${response.requestOptions.uri}');
        print('Status Code: ${response.statusCode}');
        print('Response: ${response.data}');
        return handler.next(response);
      },
      onError: (DioException e, handler) {
        print('--- API ERROR ---');
        print('URL: ${e.requestOptions.method} ${e.requestOptions.uri}');
        print('Status Code: ${e.response?.statusCode}');
        print('Response: ${e.response?.data ?? e.message}');
        return handler.next(e);
      },
    ));
  }

  Dio get client => dio;
}
