"""
Binance Derivatives Trading USDS Futures REST API

OpenAPI Specification for the Binance Derivatives Trading USDS Futures REST API
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)

Do not edit the class manually.
"""

import json
import pytest
import requests

from unittest.mock import MagicMock, patch
from urllib.parse import parse_qs

from binance_common.configuration import ConfigurationRestAPI
from binance_common.errors import RequiredError
from binance_common.utils import normalize_query_values, is_one_of_model, snake_to_camel

from binance_sdk_derivatives_trading_usds_futures.rest_api.api import ConvertApi
from binance_sdk_derivatives_trading_usds_futures.rest_api.models import (
    AcceptTheOfferedQuoteResponse,
)
from binance_sdk_derivatives_trading_usds_futures.rest_api.models import (
    ListAllConvertPairsResponse,
)
from binance_sdk_derivatives_trading_usds_futures.rest_api.models import (
    OrderStatusResponse,
)
from binance_sdk_derivatives_trading_usds_futures.rest_api.models import (
    SendQuoteRequestResponse,
)


class TestConvertApi:
    @pytest.fixture(autouse=True)
    def setup_client(self):
        """Setup a client instance with mocked session before each test method."""
        self.mock_session = MagicMock(spec=requests.Session)
        config = ConfigurationRestAPI(
            api_key="test-api-key",
            api_secret="test-api-secret",
        )
        self.client = ConvertApi(configuration=config, session=self.mock_session)

    def set_mock_response(self, data: dict = {}, status_code=200, headers=None):
        """Helper method to setup mock response for the client's session request."""
        if headers is None:
            headers = {}

        mock_response = MagicMock()
        mock_response.status_code = status_code
        mock_response.json.return_value = data
        mock_response.text = json.dumps(data)
        mock_response.headers = headers

        self.mock_session.request.return_value = mock_response

    @patch("binance_common.utils.get_signature")
    def test_accept_the_offered_quote_success(self, mock_get_signature):
        """Test accept_the_offered_quote() successfully with required parameters only."""

        params = {
            "quote_id": "1",
        }

        expected_response = {
            "orderId": "933256278426274426",
            "createTime": 1623381330472,
            "orderStatus": "PROCESS",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.accept_the_offered_quote(**params)

        actual_call_args = self.mock_session.request.call_args
        request_kwargs = actual_call_args.kwargs
        parsed_params = parse_qs(request_kwargs["params"])
        camel_case_params = {snake_to_camel(k): v for k, v in params.items()}
        normalized = normalize_query_values(parsed_params, camel_case_params)

        self.mock_session.request.assert_called_once()
        mock_get_signature.assert_called_once()

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/fapi/v1/convert/acceptQuote" in request_kwargs["url"]
        assert request_kwargs["method"] == "POST"
        assert normalized["quoteId"] == "1"

        assert response is not None
        is_list = isinstance(expected_response, list)
        is_flat_list = (
            is_list and not isinstance(expected_response[0], list) if is_list else False
        )
        is_oneof = is_one_of_model(AcceptTheOfferedQuoteResponse)

        if is_list and not is_flat_list:
            expected = expected_response
        elif is_oneof or is_list or hasattr(AcceptTheOfferedQuoteResponse, "from_dict"):
            expected = AcceptTheOfferedQuoteResponse.from_dict(expected_response)
        else:
            expected = AcceptTheOfferedQuoteResponse.model_validate_json(
                json.dumps(expected_response)
            )

        assert response.data() == expected

    @patch("binance_common.utils.get_signature")
    def test_accept_the_offered_quote_success_with_optional_params(
        self, mock_get_signature
    ):
        """Test accept_the_offered_quote() successfully with optional parameters."""

        params = {"quote_id": "1", "recv_window": 5000}

        expected_response = {
            "orderId": "933256278426274426",
            "createTime": 1623381330472,
            "orderStatus": "PROCESS",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.accept_the_offered_quote(**params)

        actual_call_args = self.mock_session.request.call_args
        request_kwargs = actual_call_args.kwargs

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/fapi/v1/convert/acceptQuote" in request_kwargs["url"]
        assert request_kwargs["method"] == "POST"

        self.mock_session.request.assert_called_once()
        assert response is not None
        is_list = isinstance(expected_response, list)
        is_flat_list = (
            is_list and not isinstance(expected_response[0], list) if is_list else False
        )
        is_oneof = is_one_of_model(AcceptTheOfferedQuoteResponse)

        if is_list and not is_flat_list:
            expected = expected_response
        elif is_oneof or is_list or hasattr(AcceptTheOfferedQuoteResponse, "from_dict"):
            expected = AcceptTheOfferedQuoteResponse.from_dict(expected_response)
        else:
            expected = AcceptTheOfferedQuoteResponse.model_validate_json(
                json.dumps(expected_response)
            )

        assert response.data() == expected

    def test_accept_the_offered_quote_missing_required_param_quote_id(self):
        """Test that accept_the_offered_quote() raises RequiredError when 'quote_id' is missing."""
        params = {
            "quote_id": "1",
        }
        params["quote_id"] = None

        with pytest.raises(
            RequiredError, match="Missing required parameter 'quote_id'"
        ):
            self.client.accept_the_offered_quote(**params)

    def test_accept_the_offered_quote_server_error(self):
        """Test that accept_the_offered_quote() raises an error when the server returns an error."""

        params = {
            "quote_id": "1",
        }

        mock_error = Exception("ResponseError")
        self.client.accept_the_offered_quote = MagicMock(side_effect=mock_error)

        with pytest.raises(Exception, match="ResponseError"):
            self.client.accept_the_offered_quote(**params)

    def test_list_all_convert_pairs_success(self):
        """Test list_all_convert_pairs() successfully with required parameters only."""

        expected_response = [
            {
                "fromAsset": "BTC",
                "toAsset": "USDT",
                "fromAssetMinAmount": "0.0004",
                "fromAssetMaxAmount": "50",
                "toAssetMinAmount": "20",
                "toAssetMaxAmount": "2500000",
            }
        ]

        self.set_mock_response(expected_response)

        response = self.client.list_all_convert_pairs()

        actual_call_args = self.mock_session.request.call_args
        request_kwargs = actual_call_args.kwargs

        self.mock_session.request.assert_called_once()

        assert "url" in request_kwargs
        assert "/fapi/v1/convert/exchangeInfo" in request_kwargs["url"]
        assert request_kwargs["method"] == "GET"

        assert response is not None
        is_list = isinstance(expected_response, list)
        is_flat_list = (
            is_list and not isinstance(expected_response[0], list) if is_list else False
        )
        is_oneof = is_one_of_model(ListAllConvertPairsResponse)

        if is_list and not is_flat_list:
            expected = expected_response
        elif is_oneof or is_list or hasattr(ListAllConvertPairsResponse, "from_dict"):
            expected = ListAllConvertPairsResponse.from_dict(expected_response)
        else:
            expected = ListAllConvertPairsResponse.model_validate_json(
                json.dumps(expected_response)
            )

        assert response.data() == expected

    def test_list_all_convert_pairs_success_with_optional_params(self):
        """Test list_all_convert_pairs() successfully with optional parameters."""

        params = {"from_asset": "from_asset_example", "to_asset": "to_asset_example"}

        expected_response = [
            {
                "fromAsset": "BTC",
                "toAsset": "USDT",
                "fromAssetMinAmount": "0.0004",
                "fromAssetMaxAmount": "50",
                "toAssetMinAmount": "20",
                "toAssetMaxAmount": "2500000",
            }
        ]

        self.set_mock_response(expected_response)

        response = self.client.list_all_convert_pairs(**params)

        actual_call_args = self.mock_session.request.call_args
        request_kwargs = actual_call_args.kwargs

        assert "url" in request_kwargs
        assert "/fapi/v1/convert/exchangeInfo" in request_kwargs["url"]
        assert request_kwargs["method"] == "GET"

        self.mock_session.request.assert_called_once()
        assert response is not None
        is_list = isinstance(expected_response, list)
        is_flat_list = (
            is_list and not isinstance(expected_response[0], list) if is_list else False
        )
        is_oneof = is_one_of_model(ListAllConvertPairsResponse)

        if is_list and not is_flat_list:
            expected = expected_response
        elif is_oneof or is_list or hasattr(ListAllConvertPairsResponse, "from_dict"):
            expected = ListAllConvertPairsResponse.from_dict(expected_response)
        else:
            expected = ListAllConvertPairsResponse.model_validate_json(
                json.dumps(expected_response)
            )

        assert response.data() == expected

    def test_list_all_convert_pairs_server_error(self):
        """Test that list_all_convert_pairs() raises an error when the server returns an error."""

        mock_error = Exception("ResponseError")
        self.client.list_all_convert_pairs = MagicMock(side_effect=mock_error)

        with pytest.raises(Exception, match="ResponseError"):
            self.client.list_all_convert_pairs()

    @patch("binance_common.utils.get_signature")
    def test_order_status_success(self, mock_get_signature):
        """Test order_status() successfully with required parameters only."""

        expected_response = {
            "orderId": 933256278426274400,
            "orderStatus": "SUCCESS",
            "fromAsset": "BTC",
            "fromAmount": "0.00054414",
            "toAsset": "USDT",
            "toAmount": "20",
            "ratio": "36755",
            "inverseRatio": "0.00002721",
            "createTime": 1623381330472,
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.order_status()

        actual_call_args = self.mock_session.request.call_args
        request_kwargs = actual_call_args.kwargs

        self.mock_session.request.assert_called_once()
        mock_get_signature.assert_called_once()

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/fapi/v1/convert/orderStatus" in request_kwargs["url"]
        assert request_kwargs["method"] == "GET"

        assert response is not None
        is_list = isinstance(expected_response, list)
        is_flat_list = (
            is_list and not isinstance(expected_response[0], list) if is_list else False
        )
        is_oneof = is_one_of_model(OrderStatusResponse)

        if is_list and not is_flat_list:
            expected = expected_response
        elif is_oneof or is_list or hasattr(OrderStatusResponse, "from_dict"):
            expected = OrderStatusResponse.from_dict(expected_response)
        else:
            expected = OrderStatusResponse.model_validate_json(
                json.dumps(expected_response)
            )

        assert response.data() == expected

    @patch("binance_common.utils.get_signature")
    def test_order_status_success_with_optional_params(self, mock_get_signature):
        """Test order_status() successfully with optional parameters."""

        params = {"order_id": "1", "quote_id": "1"}

        expected_response = {
            "orderId": 933256278426274400,
            "orderStatus": "SUCCESS",
            "fromAsset": "BTC",
            "fromAmount": "0.00054414",
            "toAsset": "USDT",
            "toAmount": "20",
            "ratio": "36755",
            "inverseRatio": "0.00002721",
            "createTime": 1623381330472,
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.order_status(**params)

        actual_call_args = self.mock_session.request.call_args
        request_kwargs = actual_call_args.kwargs

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/fapi/v1/convert/orderStatus" in request_kwargs["url"]
        assert request_kwargs["method"] == "GET"

        self.mock_session.request.assert_called_once()
        assert response is not None
        is_list = isinstance(expected_response, list)
        is_flat_list = (
            is_list and not isinstance(expected_response[0], list) if is_list else False
        )
        is_oneof = is_one_of_model(OrderStatusResponse)

        if is_list and not is_flat_list:
            expected = expected_response
        elif is_oneof or is_list or hasattr(OrderStatusResponse, "from_dict"):
            expected = OrderStatusResponse.from_dict(expected_response)
        else:
            expected = OrderStatusResponse.model_validate_json(
                json.dumps(expected_response)
            )

        assert response.data() == expected

    def test_order_status_server_error(self):
        """Test that order_status() raises an error when the server returns an error."""

        mock_error = Exception("ResponseError")
        self.client.order_status = MagicMock(side_effect=mock_error)

        with pytest.raises(Exception, match="ResponseError"):
            self.client.order_status()

    @patch("binance_common.utils.get_signature")
    def test_send_quote_request_success(self, mock_get_signature):
        """Test send_quote_request() successfully with required parameters only."""

        params = {
            "from_asset": "from_asset_example",
            "to_asset": "to_asset_example",
        }

        expected_response = {
            "quoteId": "12415572564",
            "ratio": "38163.7",
            "inverseRatio": "0.0000262",
            "validTimestamp": 1623319461670,
            "toAmount": "3816.37",
            "fromAmount": "0.1",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.send_quote_request(**params)

        actual_call_args = self.mock_session.request.call_args
        request_kwargs = actual_call_args.kwargs
        parsed_params = parse_qs(request_kwargs["params"])
        camel_case_params = {snake_to_camel(k): v for k, v in params.items()}
        normalized = normalize_query_values(parsed_params, camel_case_params)

        self.mock_session.request.assert_called_once()
        mock_get_signature.assert_called_once()

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/fapi/v1/convert/getQuote" in request_kwargs["url"]
        assert request_kwargs["method"] == "POST"
        assert normalized["fromAsset"] == "from_asset_example"
        assert normalized["toAsset"] == "to_asset_example"

        assert response is not None
        is_list = isinstance(expected_response, list)
        is_flat_list = (
            is_list and not isinstance(expected_response[0], list) if is_list else False
        )
        is_oneof = is_one_of_model(SendQuoteRequestResponse)

        if is_list and not is_flat_list:
            expected = expected_response
        elif is_oneof or is_list or hasattr(SendQuoteRequestResponse, "from_dict"):
            expected = SendQuoteRequestResponse.from_dict(expected_response)
        else:
            expected = SendQuoteRequestResponse.model_validate_json(
                json.dumps(expected_response)
            )

        assert response.data() == expected

    @patch("binance_common.utils.get_signature")
    def test_send_quote_request_success_with_optional_params(self, mock_get_signature):
        """Test send_quote_request() successfully with optional parameters."""

        params = {
            "from_asset": "from_asset_example",
            "to_asset": "to_asset_example",
            "from_amount": 1.0,
            "to_amount": 1.0,
            "valid_time": "10s",
            "recv_window": 5000,
        }

        expected_response = {
            "quoteId": "12415572564",
            "ratio": "38163.7",
            "inverseRatio": "0.0000262",
            "validTimestamp": 1623319461670,
            "toAmount": "3816.37",
            "fromAmount": "0.1",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.send_quote_request(**params)

        actual_call_args = self.mock_session.request.call_args
        request_kwargs = actual_call_args.kwargs

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/fapi/v1/convert/getQuote" in request_kwargs["url"]
        assert request_kwargs["method"] == "POST"

        self.mock_session.request.assert_called_once()
        assert response is not None
        is_list = isinstance(expected_response, list)
        is_flat_list = (
            is_list and not isinstance(expected_response[0], list) if is_list else False
        )
        is_oneof = is_one_of_model(SendQuoteRequestResponse)

        if is_list and not is_flat_list:
            expected = expected_response
        elif is_oneof or is_list or hasattr(SendQuoteRequestResponse, "from_dict"):
            expected = SendQuoteRequestResponse.from_dict(expected_response)
        else:
            expected = SendQuoteRequestResponse.model_validate_json(
                json.dumps(expected_response)
            )

        assert response.data() == expected

    def test_send_quote_request_missing_required_param_from_asset(self):
        """Test that send_quote_request() raises RequiredError when 'from_asset' is missing."""
        params = {
            "from_asset": "from_asset_example",
            "to_asset": "to_asset_example",
        }
        params["from_asset"] = None

        with pytest.raises(
            RequiredError, match="Missing required parameter 'from_asset'"
        ):
            self.client.send_quote_request(**params)

    def test_send_quote_request_missing_required_param_to_asset(self):
        """Test that send_quote_request() raises RequiredError when 'to_asset' is missing."""
        params = {
            "from_asset": "from_asset_example",
            "to_asset": "to_asset_example",
        }
        params["to_asset"] = None

        with pytest.raises(
            RequiredError, match="Missing required parameter 'to_asset'"
        ):
            self.client.send_quote_request(**params)

    def test_send_quote_request_server_error(self):
        """Test that send_quote_request() raises an error when the server returns an error."""

        params = {
            "from_asset": "from_asset_example",
            "to_asset": "to_asset_example",
        }

        mock_error = Exception("ResponseError")
        self.client.send_quote_request = MagicMock(side_effect=mock_error)

        with pytest.raises(Exception, match="ResponseError"):
            self.client.send_quote_request(**params)
