# [DEF:backend.src.core.auth.jwt:Module]
#
# @TIER:      STANDARD
# @SEMANTICS: jwt, token, session, auth
# @PURPOSE:   JWT token generation and validation logic.
# @LAYER:     Core
# @RELATION:  DEPENDS_ON -> jose
# @RELATION:  USES -> backend.src.core.auth.config.auth_config
#
# @INVARIANT: Tokens must include expiration time and user identifier.

# [SECTION: IMPORTS]
from datetime import datetime, timedelta
from typing import Optional
from jose import jwt
from .config import auth_config
from ..logger import belief_scope
# [/SECTION]

# [DEF:create_access_token:Function]
# @PURPOSE: Generates a new JWT access token.
# @PRE:     data dict contains 'sub' (user_id) and optional 'scopes' (roles).
# @POST:    Returns a signed JWT string.
#
# @PARAM:   data (dict) - Payload data for the token.
# @PARAM:   expires_delta (Optional[timedelta]) - Custom expiration time.
# @RETURN:  str - The encoded JWT.
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
    with belief_scope("create_access_token"):
        to_encode = data.copy()
        if expires_delta:
            expire = datetime.utcnow() + expires_delta
        else:
            expire = datetime.utcnow() + timedelta(minutes=auth_config.ACCESS_TOKEN_EXPIRE_MINUTES)
        
        to_encode.update({"exp": expire})
        encoded_jwt = jwt.encode(to_encode, auth_config.SECRET_KEY, algorithm=auth_config.ALGORITHM)
        return encoded_jwt
# [/DEF:create_access_token:Function]

# [DEF:decode_token:Function]
# @PURPOSE: Decodes and validates a JWT token.
# @PRE:     token is a signed JWT string.
# @POST:    Returns the decoded payload if valid.
#
# @PARAM:   token (str) - The JWT to decode.
# @RETURN:  dict - The decoded payload.
# @THROW:   jose.JWTError - If token is invalid or expired.
def decode_token(token: str) -> dict:
    with belief_scope("decode_token"):
        payload = jwt.decode(token, auth_config.SECRET_KEY, algorithms=[auth_config.ALGORITHM])
        return payload
# [/DEF:decode_token:Function]

# [/DEF:backend.src.core.auth.jwt:Module]