"""JWT token creation and validation"""

from datetime import datetime, timedelta, timezone
from typing import Optional

from jose import jwt, JWTError

from web.backend.config import get_or_generate_secret, JWT_ALGORITHM, JWT_EXPIRE_HOURS


def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
    to_encode = data.copy()
    expire = datetime.now(timezone.utc) + (expires_delta or timedelta(hours=JWT_EXPIRE_HOURS))
    to_encode.update({"exp": expire})
    return jwt.encode(to_encode, get_or_generate_secret(), algorithm=JWT_ALGORITHM)


def decode_token(token: str) -> dict:
    return jwt.decode(token, get_or_generate_secret(), algorithms=[JWT_ALGORITHM])
