import base64
import binascii
from typing import Optional
from ws_package.configs import config
from ws_package.log.writer import LogWriter

logger = LogWriter.file(__name__)


class TokenValidator():
    def __init__(self, validate_b64: Optional[bool] = False):
        self.decoded_data = None  # Instance-specific state to prevent shared mutable state
        self.validate_b64 = validate_b64

    def __call__(self, content) -> str:
        if self.validate_b64:
            try:
                self.decoded_data = base64.b64decode(content)
            except binascii.Error as e:
                logger.error("%s Token is not a base64 string", e)
                raise ValueError("Invalid Token Format: Token is not a base64 string.")
        return content
        
    @property
    def data(self):
        return self.decoded_data
class TokenReader:
    def __init__(
            self,
        ) -> None:
        key = config('user_token_key', 'Application')
        self.user_token_key = TokenValidator()  # Instance-specific state to prevent shared mutable state
        self.user_token_key = self.user_token_key(key)

    @property
    def value(self):
        return self.user_token_key
    
    def __call__(self):
        return self.value


get_user_token = TokenReader()
