"""
Binance Sub Account REST API

OpenAPI Specification for the Binance Sub Account 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_sub_account.rest_api.api import ApiManagementApi
from binance_sdk_sub_account.rest_api.models import (
    AddIpRestrictionForSubAccountApiKeyResponse,
)
from binance_sdk_sub_account.rest_api.models import (
    DeleteIpListForASubAccountApiKeyResponse,
)
from binance_sdk_sub_account.rest_api.models import (
    GetIpRestrictionForASubAccountApiKeyResponse,
)


class TestApiManagementApi:
    @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 = ApiManagementApi(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_add_ip_restriction_for_sub_account_api_key_success(
        self, mock_get_signature
    ):
        """Test add_ip_restriction_for_sub_account_api_key() successfully with required parameters only."""

        params = {
            "email": "sub-account-email@email.com",
            "sub_account_api_key": "sub_account_api_key_example",
            "status": "status_example",
        }

        expected_response = {
            "status": "2",
            "ipList": ["69.210.67.14", "8.34.21.10"],
            "updateTime": 1636371437000,
            "apiKey": "k5V49ldtn4tszj6W3hystegdfvmGbqDzjmkCtpTvC0G74WhK7yd4rfCTo4lShf",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.add_ip_restriction_for_sub_account_api_key(**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/v2/sub-account/subAccountApi/ipRestriction" in request_kwargs["url"]
        )
        assert request_kwargs["method"] == "POST"
        assert normalized["email"] == "sub-account-email@email.com"
        assert normalized["subAccountApiKey"] == "sub_account_api_key_example"
        assert normalized["status"] == "status_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(AddIpRestrictionForSubAccountApiKeyResponse)

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

        assert response.data() == expected

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

        params = {
            "email": "sub-account-email@email.com",
            "sub_account_api_key": "sub_account_api_key_example",
            "status": "status_example",
            "ip_address": "ip_address_example",
            "recv_window": 5000,
        }

        expected_response = {
            "status": "2",
            "ipList": ["69.210.67.14", "8.34.21.10"],
            "updateTime": 1636371437000,
            "apiKey": "k5V49ldtn4tszj6W3hystegdfvmGbqDzjmkCtpTvC0G74WhK7yd4rfCTo4lShf",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.add_ip_restriction_for_sub_account_api_key(**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/v2/sub-account/subAccountApi/ipRestriction" 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(AddIpRestrictionForSubAccountApiKeyResponse)

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

        assert response.data() == expected

    def test_add_ip_restriction_for_sub_account_api_key_missing_required_param_email(
        self,
    ):
        """Test that add_ip_restriction_for_sub_account_api_key() raises RequiredError when 'email' is missing."""
        params = {
            "email": "sub-account-email@email.com",
            "sub_account_api_key": "sub_account_api_key_example",
            "status": "status_example",
        }
        params["email"] = None

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

    def test_add_ip_restriction_for_sub_account_api_key_missing_required_param_sub_account_api_key(
        self,
    ):
        """Test that add_ip_restriction_for_sub_account_api_key() raises RequiredError when 'sub_account_api_key' is missing."""
        params = {
            "email": "sub-account-email@email.com",
            "sub_account_api_key": "sub_account_api_key_example",
            "status": "status_example",
        }
        params["sub_account_api_key"] = None

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

    def test_add_ip_restriction_for_sub_account_api_key_missing_required_param_status(
        self,
    ):
        """Test that add_ip_restriction_for_sub_account_api_key() raises RequiredError when 'status' is missing."""
        params = {
            "email": "sub-account-email@email.com",
            "sub_account_api_key": "sub_account_api_key_example",
            "status": "status_example",
        }
        params["status"] = None

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

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

        params = {
            "email": "sub-account-email@email.com",
            "sub_account_api_key": "sub_account_api_key_example",
            "status": "status_example",
        }

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

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

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

        params = {
            "email": "sub-account-email@email.com",
            "sub_account_api_key": "sub_account_api_key_example",
            "ip_address": "ip_address_example",
        }

        expected_response = {
            "ipRestrict": "True",
            "ipList": ["69.210.67.14", "8.34.21.10"],
            "updateTime": 1636371437000,
            "apiKey": "k5V49ldtn4tszj6W3hystegdfvmGbqDzjmkCtpTvC0G74WhK7yd4rfCTo4lShf",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.delete_ip_list_for_a_sub_account_api_key(**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/sub-account/subAccountApi/ipRestriction/ipList"
            in request_kwargs["url"]
        )
        assert request_kwargs["method"] == "DELETE"
        assert normalized["email"] == "sub-account-email@email.com"
        assert normalized["subAccountApiKey"] == "sub_account_api_key_example"
        assert normalized["ipAddress"] == "ip_address_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(DeleteIpListForASubAccountApiKeyResponse)

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

        assert response.data() == expected

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

        params = {
            "email": "sub-account-email@email.com",
            "sub_account_api_key": "sub_account_api_key_example",
            "ip_address": "ip_address_example",
            "recv_window": 5000,
        }

        expected_response = {
            "ipRestrict": "True",
            "ipList": ["69.210.67.14", "8.34.21.10"],
            "updateTime": 1636371437000,
            "apiKey": "k5V49ldtn4tszj6W3hystegdfvmGbqDzjmkCtpTvC0G74WhK7yd4rfCTo4lShf",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.delete_ip_list_for_a_sub_account_api_key(**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/sub-account/subAccountApi/ipRestriction/ipList"
            in request_kwargs["url"]
        )
        assert request_kwargs["method"] == "DELETE"

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

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

        assert response.data() == expected

    def test_delete_ip_list_for_a_sub_account_api_key_missing_required_param_email(
        self,
    ):
        """Test that delete_ip_list_for_a_sub_account_api_key() raises RequiredError when 'email' is missing."""
        params = {
            "email": "sub-account-email@email.com",
            "sub_account_api_key": "sub_account_api_key_example",
            "ip_address": "ip_address_example",
        }
        params["email"] = None

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

    def test_delete_ip_list_for_a_sub_account_api_key_missing_required_param_sub_account_api_key(
        self,
    ):
        """Test that delete_ip_list_for_a_sub_account_api_key() raises RequiredError when 'sub_account_api_key' is missing."""
        params = {
            "email": "sub-account-email@email.com",
            "sub_account_api_key": "sub_account_api_key_example",
            "ip_address": "ip_address_example",
        }
        params["sub_account_api_key"] = None

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

    def test_delete_ip_list_for_a_sub_account_api_key_missing_required_param_ip_address(
        self,
    ):
        """Test that delete_ip_list_for_a_sub_account_api_key() raises RequiredError when 'ip_address' is missing."""
        params = {
            "email": "sub-account-email@email.com",
            "sub_account_api_key": "sub_account_api_key_example",
            "ip_address": "ip_address_example",
        }
        params["ip_address"] = None

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

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

        params = {
            "email": "sub-account-email@email.com",
            "sub_account_api_key": "sub_account_api_key_example",
            "ip_address": "ip_address_example",
        }

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

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

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

        params = {
            "email": "sub-account-email@email.com",
            "sub_account_api_key": "sub_account_api_key_example",
        }

        expected_response = {
            "ipRestrict": "True",
            "ipList": ["69.210.67.14", "8.34.21.10"],
            "updateTime": 1636371437000,
            "apiKey": "k5V49ldtn4tszj6W3hystegdfvmGbqDzjmkCtpTvC0G74WhK7yd4rfCTo4lShf",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_ip_restriction_for_a_sub_account_api_key(**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/sub-account/subAccountApi/ipRestriction" in request_kwargs["url"]
        )
        assert request_kwargs["method"] == "GET"
        assert normalized["email"] == "sub-account-email@email.com"
        assert normalized["subAccountApiKey"] == "sub_account_api_key_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(GetIpRestrictionForASubAccountApiKeyResponse)

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

        assert response.data() == expected

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

        params = {
            "email": "sub-account-email@email.com",
            "sub_account_api_key": "sub_account_api_key_example",
            "recv_window": 5000,
        }

        expected_response = {
            "ipRestrict": "True",
            "ipList": ["69.210.67.14", "8.34.21.10"],
            "updateTime": 1636371437000,
            "apiKey": "k5V49ldtn4tszj6W3hystegdfvmGbqDzjmkCtpTvC0G74WhK7yd4rfCTo4lShf",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_ip_restriction_for_a_sub_account_api_key(**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/sub-account/subAccountApi/ipRestriction" 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(GetIpRestrictionForASubAccountApiKeyResponse)

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

        assert response.data() == expected

    def test_get_ip_restriction_for_a_sub_account_api_key_missing_required_param_email(
        self,
    ):
        """Test that get_ip_restriction_for_a_sub_account_api_key() raises RequiredError when 'email' is missing."""
        params = {
            "email": "sub-account-email@email.com",
            "sub_account_api_key": "sub_account_api_key_example",
        }
        params["email"] = None

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

    def test_get_ip_restriction_for_a_sub_account_api_key_missing_required_param_sub_account_api_key(
        self,
    ):
        """Test that get_ip_restriction_for_a_sub_account_api_key() raises RequiredError when 'sub_account_api_key' is missing."""
        params = {
            "email": "sub-account-email@email.com",
            "sub_account_api_key": "sub_account_api_key_example",
        }
        params["sub_account_api_key"] = None

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

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

        params = {
            "email": "sub-account-email@email.com",
            "sub_account_api_key": "sub_account_api_key_example",
        }

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

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