"""
Binance Staking REST API

OpenAPI Specification for the Binance Staking 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_staking.rest_api.api import SoftStakingApi
from binance_sdk_staking.rest_api.models import GetSoftStakingProductListResponse
from binance_sdk_staking.rest_api.models import GetSoftStakingRewardsHistoryResponse
from binance_sdk_staking.rest_api.models import SetSoftStakingResponse


class TestSoftStakingApi:
    @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 = SoftStakingApi(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_soft_staking_product_list_success(self, mock_get_signature):
        """Test get_soft_staking_product_list() successfully with required parameters only."""

        expected_response = {
            "status": True,
            "totalRewardsUsdt": "3.09827182",
            "rows": [
                {
                    "asset": "BNB",
                    "minAmount": "0.5",
                    "maxCap": "1000",
                    "apr": "0.0015",
                    "stakedAmount": "2.14",
                    "totalProfit": "0.00171234",
                },
                {
                    "asset": "SUI",
                    "minAmount": "100",
                    "maxCap": "50000",
                    "apr": "0.01",
                    "stakedAmount": "100",
                    "totalProfit": "0.1",
                },
            ],
            "total": 2,
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_soft_staking_product_list()

        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/soft-staking/list" 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(GetSoftStakingProductListResponse)

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

        assert response.data() == expected

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

        params = {"asset": "BETH", "current": 1, "size": 10, "recv_window": 5000}

        expected_response = {
            "status": True,
            "totalRewardsUsdt": "3.09827182",
            "rows": [
                {
                    "asset": "BNB",
                    "minAmount": "0.5",
                    "maxCap": "1000",
                    "apr": "0.0015",
                    "stakedAmount": "2.14",
                    "totalProfit": "0.00171234",
                },
                {
                    "asset": "SUI",
                    "minAmount": "100",
                    "maxCap": "50000",
                    "apr": "0.01",
                    "stakedAmount": "100",
                    "totalProfit": "0.1",
                },
            ],
            "total": 2,
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_soft_staking_product_list(**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/soft-staking/list" 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(GetSoftStakingProductListResponse)

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

        assert response.data() == expected

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

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

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

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

        expected_response = {
            "rows": [
                {
                    "asset": "BNB",
                    "rewards": "0.00000557",
                    "rewardAsset": "BNB",
                    "avgAmount": "2.14",
                    "time": 1754007978000,
                },
                {
                    "asset": "SUI",
                    "rewards": "0.00274257",
                    "rewardAsset": "SUI",
                    "avgAmount": "100",
                    "time": 1754007978000,
                },
            ],
            "total": 2,
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_soft_staking_rewards_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/soft-staking/history/rewardsRecord" 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(GetSoftStakingRewardsHistoryResponse)

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

        assert response.data() == expected

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

        params = {
            "asset": "BETH",
            "start_time": 1623319461670,
            "end_time": 1641782889000,
            "current": 1,
            "size": 10,
            "recv_window": 5000,
        }

        expected_response = {
            "rows": [
                {
                    "asset": "BNB",
                    "rewards": "0.00000557",
                    "rewardAsset": "BNB",
                    "avgAmount": "2.14",
                    "time": 1754007978000,
                },
                {
                    "asset": "SUI",
                    "rewards": "0.00274257",
                    "rewardAsset": "SUI",
                    "avgAmount": "100",
                    "time": 1754007978000,
                },
            ],
            "total": 2,
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_soft_staking_rewards_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/soft-staking/history/rewardsRecord" 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(GetSoftStakingRewardsHistoryResponse)

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

        assert response.data() == expected

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

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

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

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

        params = {
            "soft_staking": True,
        }

        expected_response = {"success": True}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.set_soft_staking(**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/soft-staking/set" in request_kwargs["url"]
        assert request_kwargs["method"] == "GET"
        assert normalized["softStaking"] 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(SetSoftStakingResponse)

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

        assert response.data() == expected

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

        params = {"soft_staking": True, "recv_window": 5000}

        expected_response = {"success": True}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.set_soft_staking(**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/soft-staking/set" 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(SetSoftStakingResponse)

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

        assert response.data() == expected

    def test_set_soft_staking_missing_required_param_soft_staking(self):
        """Test that set_soft_staking() raises RequiredError when 'soft_staking' is missing."""
        params = {
            "soft_staking": True,
        }
        params["soft_staking"] = None

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

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

        params = {
            "soft_staking": True,
        }

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

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