import 'package:autos/core/constants/api_endpoints.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';

class ApiService {
  final Dio _dio;

  ApiService({String? baseUrl})
      : _dio = Dio(
          BaseOptions(
            baseUrl: baseUrl ?? ApiEndpoints.baseUrl,
            connectTimeout: ApiEndpoints.connectTimeout,
            receiveTimeout: ApiEndpoints.receiveTimeout,
            headers: ApiEndpoints.defaultHeaders,
          ),
        ) {
    if (kDebugMode) {
      _dio.interceptors.add(
        LogInterceptor(requestBody: true, responseBody: true),
      );
    }
  }

  // ✅ KEEP OLD POST (so existing files DO NOT BREAK)
  Future<Response> post(
    String endpoint,
    Map<String, dynamic> data, {
    Options? options,
  }) async {
    return await _dio.post(endpoint, data: data, options: options);
  }

  // ✅ NEW POST (for overrideBaseUrl + headers + params)
  Future<Response> postWithOptions(
    String endpoint, {
    dynamic data,
    Map<String, dynamic>? params,
    Map<String, dynamic>? headers,
    String? overrideBaseUrl,
  }) async {
    final String requestUrl =
        overrideBaseUrl != null ? overrideBaseUrl + endpoint : endpoint;

    return await _dio.post(
      requestUrl,
      data: data,
      queryParameters: params,
      options: headers != null ? Options(headers: headers) : null,
    );
  }

  // ✅ GET (unchanged)
  Future<Response> get(
    String endpoint, {
    Map<String, dynamic>? params,
    Map<String, dynamic>? headers,
    String? overrideBaseUrl,
  }) async {
    final String requestUrl =
        overrideBaseUrl != null ? overrideBaseUrl + endpoint : endpoint;

    return await _dio.get(
      requestUrl,
      queryParameters: params,
      options: headers != null ? Options(headers: headers) : null,
    );
  }
}
