# -*- coding: utf-8 -*-
"""JWT 발급·검증 + uuid. castad app/user/services/jwt.py 패턴 축약."""
import uuid
from datetime import datetime, timedelta, timezone

from jose import JWTError, jwt

from .config import settings


def new_uuid() -> str:
    return str(uuid.uuid4())


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


def create_access_token(user_uuid: str) -> str:
    payload = {
        "sub": user_uuid, "type": "access",
        "exp": _now() + timedelta(minutes=settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES),
    }
    return jwt.encode(payload, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM)


def create_refresh_token(user_uuid: str) -> str:
    payload = {
        "sub": user_uuid, "type": "refresh",
        "exp": _now() + timedelta(days=settings.JWT_REFRESH_TOKEN_EXPIRE_DAYS),
    }
    return jwt.encode(payload, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM)


def decode_token(token: str) -> dict | None:
    try:
        return jwt.decode(token, settings.JWT_SECRET, algorithms=[settings.JWT_ALGORITHM])
    except JWTError:
        return None
