from datetime import datetime, timedelta, timezone
import jwt
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
from app.core.config import get_settings

ph = PasswordHasher()
settings = get_settings()

def hash_password(password: str) -> str:
    return ph.hash(password)

def verify_password(password: str, hashed: str) -> bool:
    try:
        return ph.verify(hashed, password)
    except VerifyMismatchError:
        return False

def create_token(user_id: int, brand_id: int, role_id: int, token_type: str, expires_delta: timedelta):
    now = datetime.now(timezone.utc)
    payload = {
        "user_id": user_id, "brand_id": brand_id, "role_id": role_id,
        "token_type": token_type, "iat": now, "exp": now + expires_delta
    }
    return jwt.encode(payload, settings.jwt_secret_key, algorithm=settings.jwt_algorithm)

def create_access_token(user_id, brand_id, role_id):
    return create_token(user_id, brand_id, role_id, "access",
                        timedelta(minutes=settings.access_token_expire_minutes))

def create_refresh_token(user_id, brand_id, role_id):
    return create_token(user_id, brand_id, role_id, "refresh",
                        timedelta(days=settings.refresh_token_expire_days))

def decode_token(token: str):
    return jwt.decode(token, settings.jwt_secret_key, algorithms=[settings.jwt_algorithm])
