# /opt/docker/dev/service_finder/backend/app/core/security.py
import bcrypt
import string
import secrets
from datetime import datetime, timedelta, timezone
from typing import Optional, Dict, Any, Tuple
from jose import jwt, JWTError
from app.core.config import settings

def verify_password(plain_password: str, hashed_password: str) -> bool:
    if not hashed_password: return False
    return bcrypt.checkpw(plain_password.encode("utf-8"), hashed_password.encode("utf-8"))

def get_password_hash(password: str) -> str:
    return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")

def create_tokens(data: Dict[str, Any]) -> Tuple[str, str]:
    """ Access és Refresh token generálása UTC időzónával. """
    to_encode = data.copy()
    now = datetime.now(timezone.utc)
    
    # Access Token
    acc_expire = now + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_payload = {**to_encode, "exp": acc_expire, "iat": now, "type": "access"}
    access_token = jwt.encode(access_payload, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
    
    # Refresh Token
    ref_expire = now + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS)
    refresh_payload = {"sub": str(to_encode.get("sub")), "exp": ref_expire, "iat": now, "type": "refresh"}
    refresh_token = jwt.encode(refresh_payload, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
    
    return access_token, refresh_token

def decode_token(token: str) -> Optional[Dict[str, Any]]:
    try:
        return jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
    except JWTError:
        return None

def generate_secure_slug(length: int = 16) -> str:
    """ Biztonságos, URL-barát véletlenszerű azonosító generálása. """
    alphabet = string.ascii_letters + string.digits
    return ''.join(secrets.choice(alphabet) for _ in range(length))

# Teljesen a margón van, így globális konstans lesz!
DEFAULT_RANK_MAP = {
    "SUPERADMIN": 100,
    "ADMIN": 90,
    "AUDITOR": 80,
    "ORGANIZATION_OWNER": 70,
    "ORGANIZATION_MANAGER": 60,
    "ORGANIZATION_MEMBER": 50,
    "SERVICE_PROVIDER": 40,
    "PREMIUM_USER": 20,
    "USER": 10,
    "GUEST": 0
}