import 'package:dio/dio.dart';
import 'package:injectable/injectable.dart';

import '../../../../core/constants/api_constants.dart';
import '../../../../core/network/dio_client.dart';
import '../models/order_model.dart';

@injectable
class OrderRemoteDataSource {
  const OrderRemoteDataSource(this._client);

  final DioClient _client;

  Future<OrderModel> createOrder({
    required String currency,
    required String pair,
    required String type,
    required String side,
    required double amount,
    double? price,
    double? stopPrice,
  }) async {
    final body = {
      'currency': currency,
      'pair': pair,
      'type': type,
      'side': side,
      'amount': amount,
    };
    if (price != null) body['price'] = price;
    if (stopPrice != null) body['stopPrice'] = stopPrice;

    final Response response = await _client.post(
      ApiConstants.createOrder,
      data: body,
    );

    final data = response.data is Map<String, dynamic>
        ? response.data as Map<String, dynamic>
        : (response.data['data'] as Map<String, dynamic>);

    return OrderModel.fromJson(data);
  }

  Future<List<OrderModel>> fetchOpenOrders({required String symbol}) async {
    final parts = symbol.split('/');
    final currency = parts.first;
    final pair = parts.length > 1 ? parts[1] : '';

    final Response response = await _client.get(
      ApiConstants.orders,
      queryParameters: {
        'currency': currency,
        'pair': pair,
        'type': 'OPEN',
      },
    );

    final List<dynamic> items = response.data is List
        ? response.data as List<dynamic>
        : (response.data['data'] as List<dynamic>);

    return items
        .map((json) => OrderModel.fromJson(json as Map<String, dynamic>))
        .toList();
  }

  Future<List<OrderModel>> fetchOrderHistory({required String symbol}) async {
    final parts = symbol.split('/');
    final currency = parts.first;
    final pair = parts.length > 1 ? parts[1] : '';

    final Response response = await _client.get(
      ApiConstants.orderHistory,
      queryParameters: {
        'currency': currency,
        'pair': pair,
        'type': 'CLOSED',
      },
    );

    final List<dynamic> items = response.data is List
        ? response.data as List<dynamic>
        : (response.data['data'] as List<dynamic>);

    return items
        .map((json) => OrderModel.fromJson(json as Map<String, dynamic>))
        .toList();
  }
}
