from gumband_python_sdk.network_handler import NetworkHandler
from gumband_python_sdk.logging_handler import get_local_logger
from gumband_python_sdk.service_name import ServiceName

logger = get_local_logger()

SERVICE = ServiceName.AUTH


class AuthService:
    """
    AuthService
    ============
    A service class for managing component authentication with the Gumband API.
    This class is intended as a private class. Please use the Gumband service instead.
    """

    def __init__(self, exhibit_id: int, token: str, network_handler: NetworkHandler):
        """
        Initializes the AuthService.

        Args:
            exhibit_id (int): The unique identifier for the component.
            token (str): The authentication token associated with the component.
            network_handler (NetworkHandler): Handles network requests to the Gumband API.
        """
        self.exhibit_id = exhibit_id
        self.token = token
        self.network_handler = network_handler
        logger.debug(
            f"AuthService initialized for exhibit {exhibit_id}.",
        )

    async def authenticate(self):
        """
        Authenticates the SDK component with the Gumband API.

        This method sends the component ID and token to the `/exhibit/authenticate` endpoint.
        If authentication is successful, it retrieves the JWT token from the API response cookies
        and updates the network handler for subsequent API calls.

        Raises:
            Exception: If the authentication fails or the JWT token is not found in the response.
        """
        endpoint = "/exhibit/authenticate"
        data = {"exhibitId": self.exhibit_id, "token": self.token}
        logger.info(f"Authenticating exhibit {self.exhibit_id}")
        response = await self.network_handler.post(service=SERVICE, endpoint=endpoint, data=data)

        # Assuming the JWT is returned in the response cookies
        jwt = self.network_handler.session.cookies.get("exhibitToken")
        if jwt:
            self.network_handler.set_jwt(jwt)
            logger.info("Authentication successful.")
        else:
            logger.error("Authentication failed: JWT not found in cookies.")
            raise Exception("Authentication failed: JWT not found in cookies.")
