import 'package:dio/dio.dart';
import '../constants/app_constants.dart';
import '../storage/token_storage.dart';

class ApiClient {
  static final ApiClient _instance = ApiClient._();
  late final Dio _dio;

  ApiClient._() {
    _dio = Dio(BaseOptions(
      baseUrl: AppConstants.baseUrl,
      connectTimeout: const Duration(seconds: 10),
      receiveTimeout: const Duration(seconds: 30),
      headers: {'Content-Type': 'application/json'},
    ));

    _dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) async {
        final token = await TokenStorage.getToken();
        if (token != null && !_shouldSkipAuthHeader(options.path)) {
          options.headers['Authorization'] = 'Bearer $token';
        }
        handler.next(options);
      },
      onResponse: (response, handler) {
        // Every successful response from this API is wrapped: { data: <payload> }
        // Unwrap it so services always receive the raw payload.
        final body = response.data;
        if (body is Map<String, dynamic> &&
            body.length == 1 &&
            body.containsKey('data')) {
          response.data = body['data'];
        }
        handler.next(response);
      },
      onError: (e, handler) {
        // Log API errors to help diagnose issues during development.
        final resp = e.response;
        if (resp != null) {
          // ignore: avoid_print
          print('[API] ${e.requestOptions.method} ${e.requestOptions.path} → ${resp.statusCode}: ${resp.data}');
        }
        handler.next(e);
      },
    ));
  }

  static ApiClient get instance => _instance;

  bool _shouldSkipAuthHeader(String path) {
    return path.endsWith('/auth/employee/login') ||
        path.endsWith('/auth/renter/login');
  }

  // baseUrl is dynamic (platform-aware), so recreate when it may have changed.
  // In practice this is called once and cached via the singleton.
  Dio get dio => _dio;

  Future<Response> get(String path, {Map<String, dynamic>? params}) =>
      _dio.get(path, queryParameters: params);

  Future<Response> post(String path, {dynamic data}) =>
      _dio.post(path, data: data);

  Future<Response> patch(String path, {dynamic data}) =>
      _dio.patch(path, data: data);

  Future<Response> put(String path, {dynamic data}) =>
      _dio.put(path, data: data);

  Future<Response> delete(String path) => _dio.delete(path);
}
