"""
Binance VIP Loan REST API

OpenAPI Specification for the Binance VIP Loan 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_vip_loan.rest_api.api import TradeApi
from binance_sdk_vip_loan.rest_api.models import VipLoanBorrowResponse
from binance_sdk_vip_loan.rest_api.models import VipLoanRenewResponse
from binance_sdk_vip_loan.rest_api.models import VipLoanRepayResponse


class TestTradeApi:
    @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 = TradeApi(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_vip_loan_borrow_success(self, mock_get_signature):
        """Test vip_loan_borrow() successfully with required parameters only."""

        params = {
            "loan_account_id": 1,
            "loan_coin": "loan_coin_example",
            "loan_amount": 1.0,
            "collateral_account_id": "1",
            "collateral_coin": "collateral_coin_example",
            "is_flexible_rate": True,
        }

        expected_response = {
            "loanAccountId": "12345678",
            "requestId": "12345678",
            "loanCoin": "BTC",
            "isFlexibleRate": "Yes",
            "loanAmount": "100.55",
            "collateralAccountId": "12345678,12345678,12345678",
            "collateralCoin": "BUSD,USDT,ETH",
            "loanTerm": "30",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.vip_loan_borrow(**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/loan/vip/borrow" in request_kwargs["url"]
        assert request_kwargs["method"] == "POST"
        assert normalized["loanAccountId"] == 1
        assert normalized["loanCoin"] == "loan_coin_example"
        assert normalized["loanAmount"] == 1.0
        assert normalized["collateralAccountId"] == "1"
        assert normalized["collateralCoin"] == "collateral_coin_example"
        assert normalized["isFlexibleRate"] is True

        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(VipLoanBorrowResponse)

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

        assert response.data() == expected

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

        params = {
            "loan_account_id": 1,
            "loan_coin": "loan_coin_example",
            "loan_amount": 1.0,
            "collateral_account_id": "1",
            "collateral_coin": "collateral_coin_example",
            "is_flexible_rate": True,
            "loan_term": 56,
            "recv_window": 5000,
        }

        expected_response = {
            "loanAccountId": "12345678",
            "requestId": "12345678",
            "loanCoin": "BTC",
            "isFlexibleRate": "Yes",
            "loanAmount": "100.55",
            "collateralAccountId": "12345678,12345678,12345678",
            "collateralCoin": "BUSD,USDT,ETH",
            "loanTerm": "30",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.vip_loan_borrow(**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/loan/vip/borrow" 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(VipLoanBorrowResponse)

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

        assert response.data() == expected

    def test_vip_loan_borrow_missing_required_param_loan_account_id(self):
        """Test that vip_loan_borrow() raises RequiredError when 'loan_account_id' is missing."""
        params = {
            "loan_account_id": 1,
            "loan_coin": "loan_coin_example",
            "loan_amount": 1.0,
            "collateral_account_id": "1",
            "collateral_coin": "collateral_coin_example",
            "is_flexible_rate": True,
        }
        params["loan_account_id"] = None

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

    def test_vip_loan_borrow_missing_required_param_loan_coin(self):
        """Test that vip_loan_borrow() raises RequiredError when 'loan_coin' is missing."""
        params = {
            "loan_account_id": 1,
            "loan_coin": "loan_coin_example",
            "loan_amount": 1.0,
            "collateral_account_id": "1",
            "collateral_coin": "collateral_coin_example",
            "is_flexible_rate": True,
        }
        params["loan_coin"] = None

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

    def test_vip_loan_borrow_missing_required_param_loan_amount(self):
        """Test that vip_loan_borrow() raises RequiredError when 'loan_amount' is missing."""
        params = {
            "loan_account_id": 1,
            "loan_coin": "loan_coin_example",
            "loan_amount": 1.0,
            "collateral_account_id": "1",
            "collateral_coin": "collateral_coin_example",
            "is_flexible_rate": True,
        }
        params["loan_amount"] = None

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

    def test_vip_loan_borrow_missing_required_param_collateral_account_id(self):
        """Test that vip_loan_borrow() raises RequiredError when 'collateral_account_id' is missing."""
        params = {
            "loan_account_id": 1,
            "loan_coin": "loan_coin_example",
            "loan_amount": 1.0,
            "collateral_account_id": "1",
            "collateral_coin": "collateral_coin_example",
            "is_flexible_rate": True,
        }
        params["collateral_account_id"] = None

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

    def test_vip_loan_borrow_missing_required_param_collateral_coin(self):
        """Test that vip_loan_borrow() raises RequiredError when 'collateral_coin' is missing."""
        params = {
            "loan_account_id": 1,
            "loan_coin": "loan_coin_example",
            "loan_amount": 1.0,
            "collateral_account_id": "1",
            "collateral_coin": "collateral_coin_example",
            "is_flexible_rate": True,
        }
        params["collateral_coin"] = None

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

    def test_vip_loan_borrow_missing_required_param_is_flexible_rate(self):
        """Test that vip_loan_borrow() raises RequiredError when 'is_flexible_rate' is missing."""
        params = {
            "loan_account_id": 1,
            "loan_coin": "loan_coin_example",
            "loan_amount": 1.0,
            "collateral_account_id": "1",
            "collateral_coin": "collateral_coin_example",
            "is_flexible_rate": True,
        }
        params["is_flexible_rate"] = None

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

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

        params = {
            "loan_account_id": 1,
            "loan_coin": "loan_coin_example",
            "loan_amount": 1.0,
            "collateral_account_id": "1",
            "collateral_coin": "collateral_coin_example",
            "is_flexible_rate": True,
        }

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

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

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

        params = {
            "order_id": 1,
            "loan_term": 56,
        }

        expected_response = {
            "loanAccountId": "12345678",
            "loanCoin": "BTC",
            "loanAmount": "100.55",
            "collateralAccountId": "12345677,12345678,12345679",
            "collateralCoin": "BUSD,USDT,ETH",
            "loanTerm": "30",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.vip_loan_renew(**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/loan/vip/renew" in request_kwargs["url"]
        assert request_kwargs["method"] == "POST"
        assert normalized["orderId"] == 1
        assert normalized["loanTerm"] == 56

        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(VipLoanRenewResponse)

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

        assert response.data() == expected

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

        params = {"order_id": 1, "loan_term": 56, "recv_window": 5000}

        expected_response = {
            "loanAccountId": "12345678",
            "loanCoin": "BTC",
            "loanAmount": "100.55",
            "collateralAccountId": "12345677,12345678,12345679",
            "collateralCoin": "BUSD,USDT,ETH",
            "loanTerm": "30",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.vip_loan_renew(**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/loan/vip/renew" 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(VipLoanRenewResponse)

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

        assert response.data() == expected

    def test_vip_loan_renew_missing_required_param_order_id(self):
        """Test that vip_loan_renew() raises RequiredError when 'order_id' is missing."""
        params = {
            "order_id": 1,
            "loan_term": 56,
        }
        params["order_id"] = None

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

    def test_vip_loan_renew_missing_required_param_loan_term(self):
        """Test that vip_loan_renew() raises RequiredError when 'loan_term' is missing."""
        params = {
            "order_id": 1,
            "loan_term": 56,
        }
        params["loan_term"] = None

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

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

        params = {
            "order_id": 1,
            "loan_term": 56,
        }

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

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

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

        params = {
            "order_id": 1,
            "amount": 1.0,
        }

        expected_response = {
            "loanCoin": "BUSD",
            "repayAmount": "200.5",
            "remainingPrincipal": "100.5",
            "remainingInterest": "0",
            "collateralCoin": "BNB,BTC,ETH",
            "currentLTV": "0.25",
            "repayStatus": "Repaid",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.vip_loan_repay(**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/loan/vip/repay" in request_kwargs["url"]
        assert request_kwargs["method"] == "POST"
        assert normalized["orderId"] == 1
        assert normalized["amount"] == 1.0

        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(VipLoanRepayResponse)

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

        assert response.data() == expected

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

        params = {"order_id": 1, "amount": 1.0, "recv_window": 5000}

        expected_response = {
            "loanCoin": "BUSD",
            "repayAmount": "200.5",
            "remainingPrincipal": "100.5",
            "remainingInterest": "0",
            "collateralCoin": "BNB,BTC,ETH",
            "currentLTV": "0.25",
            "repayStatus": "Repaid",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.vip_loan_repay(**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/loan/vip/repay" 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(VipLoanRepayResponse)

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

        assert response.data() == expected

    def test_vip_loan_repay_missing_required_param_order_id(self):
        """Test that vip_loan_repay() raises RequiredError when 'order_id' is missing."""
        params = {
            "order_id": 1,
            "amount": 1.0,
        }
        params["order_id"] = None

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

    def test_vip_loan_repay_missing_required_param_amount(self):
        """Test that vip_loan_repay() raises RequiredError when 'amount' is missing."""
        params = {
            "order_id": 1,
            "amount": 1.0,
        }
        params["amount"] = None

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

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

        params = {
            "order_id": 1,
            "amount": 1.0,
        }

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

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