"""
Binance Margin Trading REST API

OpenAPI Specification for the Binance Margin Trading 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_margin_trading.rest_api.api import TransferApi
from binance_sdk_margin_trading.rest_api.models import (
    GetCrossMarginTransferHistoryResponse,
)
from binance_sdk_margin_trading.rest_api.models import QueryMaxTransferOutAmountResponse


class TestTransferApi:
    @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 = TransferApi(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_get_cross_margin_transfer_history_success(self, mock_get_signature):
        """Test get_cross_margin_transfer_history() successfully with required parameters only."""

        expected_response = {
            "rows": [
                {
                    "amount": "0.10000000",
                    "asset": "BNB",
                    "status": "CONFIRMED",
                    "timestamp": 1566898617,
                    "txId": 5240372201,
                    "type": "ROLL_IN",
                    "transFrom": "SPOT",
                    "transTo": "ISOLATED_MARGIN",
                },
                {
                    "amount": "5.00000000",
                    "asset": "USDT",
                    "status": "CONFIRMED",
                    "timestamp": 1566888436,
                    "txId": 5239810406,
                    "type": "ROLL_OUT",
                    "transFrom": "ISOLATED_MARGIN",
                    "transTo": "ISOLATED_MARGIN",
                    "fromSymbol": "BNBUSDT",
                    "toSymbol": "BTCUSDT",
                },
                {
                    "amount": "1.00000000",
                    "asset": "EOS",
                    "status": "CONFIRMED",
                    "timestamp": 1566888403,
                    "txId": 5239808703,
                    "type": "ROLL_IN",
                },
            ],
            "total": 3,
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_cross_margin_transfer_history()

        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 "/sapi/v1/margin/transfer" 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(GetCrossMarginTransferHistoryResponse)

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

        assert response.data() == expected

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

        params = {
            "asset": "asset_example",
            "type": "type_example",
            "start_time": 1623319461670,
            "end_time": 1641782889000,
            "current": 1,
            "size": 10,
            "isolated_symbol": "isolated_symbol_example",
            "recv_window": 5000,
        }

        expected_response = {
            "rows": [
                {
                    "amount": "0.10000000",
                    "asset": "BNB",
                    "status": "CONFIRMED",
                    "timestamp": 1566898617,
                    "txId": 5240372201,
                    "type": "ROLL_IN",
                    "transFrom": "SPOT",
                    "transTo": "ISOLATED_MARGIN",
                },
                {
                    "amount": "5.00000000",
                    "asset": "USDT",
                    "status": "CONFIRMED",
                    "timestamp": 1566888436,
                    "txId": 5239810406,
                    "type": "ROLL_OUT",
                    "transFrom": "ISOLATED_MARGIN",
                    "transTo": "ISOLATED_MARGIN",
                    "fromSymbol": "BNBUSDT",
                    "toSymbol": "BTCUSDT",
                },
                {
                    "amount": "1.00000000",
                    "asset": "EOS",
                    "status": "CONFIRMED",
                    "timestamp": 1566888403,
                    "txId": 5239808703,
                    "type": "ROLL_IN",
                },
            ],
            "total": 3,
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_cross_margin_transfer_history(**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 "/sapi/v1/margin/transfer" 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(GetCrossMarginTransferHistoryResponse)

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

        assert response.data() == expected

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

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

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

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

        params = {
            "asset": "asset_example",
        }

        expected_response = {"amount": "3.59498107"}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.query_max_transfer_out_amount(**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 "/sapi/v1/margin/maxTransferable" in request_kwargs["url"]
        assert request_kwargs["method"] == "GET"
        assert normalized["asset"] == "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(QueryMaxTransferOutAmountResponse)

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

        assert response.data() == expected

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

        params = {
            "asset": "asset_example",
            "isolated_symbol": "isolated_symbol_example",
            "recv_window": 5000,
        }

        expected_response = {"amount": "3.59498107"}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.query_max_transfer_out_amount(**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 "/sapi/v1/margin/maxTransferable" 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(QueryMaxTransferOutAmountResponse)

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

        assert response.data() == expected

    def test_query_max_transfer_out_amount_missing_required_param_asset(self):
        """Test that query_max_transfer_out_amount() raises RequiredError when 'asset' is missing."""
        params = {
            "asset": "asset_example",
        }
        params["asset"] = None

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

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

        params = {
            "asset": "asset_example",
        }

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

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