"""
Module to make API calls to User Referral service.
"""

import logging
from typing import Dict

from bw_essentials.constants.services import Services
from bw_essentials.services.api_client import ApiClient

logger = logging.getLogger(__name__)


class UserReferral(ApiClient):
    """
    Wrapper class for User Referral APIs.

    This client provides structured access to referral-related endpoints
    exposed by the User Portfolio service.
    """

    def __init__(self, service_user: str):
        """
        Initialize the UserReferral API client.

        Parameters
        ----------
        service_user : str
            Service user context used for authentication/authorization.
        """
        logger.info(f"Initializing UserReferral client for user: {service_user}")

        super().__init__(user=service_user)

        self.base_url = self.get_base_url(Services.USER_PORTFOLIO.value)
        self.name = Services.USER_PORTFOLIO.value

        self.urls = {
            "referral_signup": "userledger/referrals/signup/",
            "user_entitlements_summary": "userledger/users/{}/entitlements/summary/",
            "referrer_details": "userledger/referrals/referrer/{}/",
            "validate_referral_code": "userledger/referralcode/validate/",
        }

    def signup_referral(self, payload: Dict) -> Dict:
        """
        Register a user referral.

        Maps to:
        POST /user-portfolio/userledger/referrals/signup/

        Supported Payload Formats
        -------------------------

        Base referral signup (no bonus):
        {
            "user_id": "9999999999",
            "user_referral_code": "ABCD9999"
        }

        Referral signup with bonus (referrer included):
        {
            "user_id": "8888888888",
            "user_referral_code": "EFGH8888",
            "referee_name": "EFGH",
            "referrer_user_id": "9999999999",
            "referrer_referral_code": "ABCD9999",
            "referrer_name": "ABCD"
        }

        Parameters
        ----------
        payload : dict
            Referral signup payload.

        Returns
        -------
        dict
            Referral signup response data.
        """
        logger.info(f"In - signup_referral {payload =}")

        response = self._post(
            url=self.base_url,
            endpoint=self.urls.get("referral_signup"),
            json=payload,
        )

        logger.info(f"{response =}")
        return response.get("data")

    def signup_base_referral(
        self,
        user_id: str,
        user_referral_code: str,
    ) -> Dict:
        """
        Register a base referral without referrer bonus.

        Parameters
        ----------
        user_id : str
            User ID signing up.
        user_referral_code : str
            Referral code generated for the user.

        Returns
        -------
        dict
            API response data.
        """
        payload = {
            "user_id": user_id,
            "user_referral_code": user_referral_code,
        }

        logger.info(f"In - signup_base_referral {payload =}")
        return self.signup_referral(payload)

    def signup_referral_with_bonus(
        self,
        user_id: str,
        user_referral_code: str,
        referrer_user_id: str,
        referrer_referral_code: str,
        referee_name: str,
        referrer_name: str,
    ) -> Dict:
        """
        Register a referral with referrer bonus mapping.

        Parameters
        ----------
        user_id : str
            User ID signing up.
        user_referral_code : str
            Referral code generated for the user.
        referrer_user_id : str
            User ID of referrer.
        referrer_referral_code : str
            Referral code of referrer.
        referee_name : str
            Name of the referee.
        referrer_name : str
            Name of the referrer.

        Returns
        -------
        dict
            API response data.
        """
        payload = {
            "user_id": user_id,
            "user_referral_code": user_referral_code,
            "referee_name": referee_name,
            "referrer_user_id": referrer_user_id,
            "referrer_referral_code": referrer_referral_code,
            "referrer_name": referrer_name
        }

        logger.info(f"In - signup_referral_with_bonus {payload =}")
        return self.signup_referral(payload)

    def get_user_entitlements_summary(
        self,
        user_id: str,
        status: str = "active",
    ) -> dict:
        """
        Fetch entitlement summary for a user.

        Maps to:
        GET /user-portfolio/userledger/users/{user_id}/entitlements/summary/?status=active

        Parameters
        ----------
        user_id : str
            User identifier.
        status : str, optional
            Entitlement status filter (default: "active").

        Returns
        -------
        dict
            Entitlement summary data.
        """
        logger.info(
            "In - get_user_entitlements_summary "
            f"{user_id =}, {status =}"
        )
        endpoint = self.urls.get("user_entitlements_summary").format(user_id)
        response = self._get(
            url=self.base_url,
            endpoint=endpoint,
            params={"status": status},
        )
        logger.info(f"{response =}")
        return response.get("data")

    def get_referrer_details(self, referrer_user_id: str) -> Dict:
        """
        Fetch referrer details for a given user.

        Maps to:
        GET /user-portfolio/userledger/referrals/referrer/{referrer_user_id}/

        Parameters
        ----------
        referrer_user_id : str
            User ID of the referrer.

        Returns
        -------
        dict
            Referrer details response data.
        """
        logger.info(f"In - get_referrer_details: {referrer_user_id =}")
        endpoint = self.urls.get("referrer_details").format(referrer_user_id)
        response = self._get(
            url=self.base_url,
            endpoint=endpoint,
        )
        logger.info(f"{response =}")
        return response.get("data")

    def validate_referral_code(self, referral_code: str) -> dict:
        """
        Validate a referral code.

        Maps to:
        GET /user-portfolio/userledger/referralcode/validate/?referral_code=<code>

        Parameters
        ----------
        referral_code : str
            Referral code to validate.

        Returns
        -------
        dict
            Validation Status
        """
        status_dict = {
            "status": False
        }
        try:
            logger.info(f"In - validate_referral_code: {referral_code =}")
            response = self._get(
                url=self.base_url,
                endpoint=self.urls.get("validate_referral_code"),
                params={"referral_code": referral_code},
            )
            logger.info(f"{response =}")
            response_data = response.get("data")
            status = response_data.get("status").capitalize()
            logger.info(f"{status =}")
            status_dict['status'] = True
            return status_dict
        except Exception as exc:
            logger.info("Exception in validate_referral_code")
            logger.exception(exc)
            return status_dict
