import 'package:dio/dio.dart';

class MockApiClient {
  final Map<String, _MockHandler> _handlers = {};

  void registerHandler(String path, String method, _MockHandler handler) {
    final key = '$path:$method';
    _handlers[key] = handler;
  }

  void clearMocks() {
    _handlers.clear();
  }

  Future<Response<T>> get<T>(String path, {Options? options}) async {
    return _handleRequest('GET', path, options: options);
  }

  Future<Response<T>> post<T>(
    String path, {
    dynamic data,
    Options? options,
  }) async {
    return _handleRequest('POST', path, data: data, options: options);
  }

  Future<Response<T>> patch<T>(
    String path, {
    dynamic data,
    Options? options,
  }) async {
    return _handleRequest('PATCH', path, data: data, options: options);
  }

  Future<Response<T>> delete<T>(
    String path, {
    dynamic data,
    Options? options,
  }) async {
    return _handleRequest('DELETE', path, data: data, options: options);
  }

  Future<Response<T>> _handleRequest<T>(
    String method,
    String path, {
    dynamic data,
    Options? options,
  }) async {
    await Future.delayed(const Duration(milliseconds: 200));

    final key = '$path:$method';
    final handler = _handlers[key];

    if (handler != null) {
      final response = handler(data);
      if (response is Response) {
        return response as Response<T>;
      }
      return Response<T>(
        data: response as T?,
        statusCode: 200,
        requestOptions: RequestOptions(path: path),
      );
    }

    return Response<T>(
      data: null,
      statusCode: 404,
      requestOptions: RequestOptions(path: path),
    );
  }
}

typedef _MockHandler = dynamic Function(dynamic data);

class MockApiClientHolder {
  static MockApiClient? _instance;

  static MockApiClient get instance {
    _instance ??= MockApiClient();
    return _instance!;
  }

  static void reset() {
    _instance = null;
  }
}
