"""JWT token creation and validation."""

from datetime import datetime, timedelta, timezone

import jwt

from ..config import settings

ALGORITHM = "HS256"
_LEEWAY_SECONDS = 10


def _now_utc() -> datetime:
    return datetime.now(timezone.utc)


def create_access_token(user_id: int, role: str, token_version: int = 1) -> str:
    now = _now_utc()
    expire = now + timedelta(minutes=settings.access_token_expire_minutes)
    payload = {
        "iss": settings.jwt_issuer,
        "aud": settings.jwt_audience,
        "sub": str(user_id),
        "role": role,
        "type": "access",
        "ver": token_version,
        "iat": now,
        "exp": expire,
    }
    return jwt.encode(payload, settings.secret_key, algorithm=ALGORITHM)


def create_refresh_token(user_id: int, token_version: int = 1) -> str:
    now = _now_utc()
    expire = now + timedelta(days=settings.refresh_token_expire_days)
    payload = {
        "iss": settings.jwt_issuer,
        "aud": settings.jwt_audience,
        "sub": str(user_id),
        "type": "refresh",
        "ver": token_version,
        "iat": now,
        "exp": expire,
    }
    return jwt.encode(payload, settings.secret_key, algorithm=ALGORITHM)


def decode_token(token: str) -> dict:
    return jwt.decode(
        token,
        settings.secret_key,
        algorithms=[ALGORITHM],
        audience=settings.jwt_audience,
        issuer=settings.jwt_issuer,
        leeway=_LEEWAY_SECONDS,
        options={"require": ["exp", "sub", "iss", "aud", "type"]},
    )
