# retoor <retoor@molodetz.nl>

import asyncio
import secrets
from datetime import datetime, timedelta, timezone
from passlib.hash import pbkdf2_sha256
from devplacepy.database import get_table
from devplacepy.config import SESSION_MAX_AGE


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


def verify_password(password: str, hashed: str) -> bool:
    return pbkdf2_sha256.verify(password, hashed)


async def hash_password_async(password: str) -> str:
    return await asyncio.to_thread(pbkdf2_sha256.hash, password)


async def verify_password_async(password: str, hashed: str) -> bool:
    return await asyncio.to_thread(pbkdf2_sha256.verify, password, hashed)


def create_session(user_uid: str, max_age_seconds: int = SESSION_MAX_AGE) -> str:
    token = secrets.token_hex(32)
    expires_at = datetime.now(timezone.utc) + timedelta(seconds=max_age_seconds)
    sessions = get_table("sessions")
    sessions.insert(
        {
            "session_token": token,
            "user_uid": user_uid,
            "created_at": datetime.now(timezone.utc).isoformat(),
            "expires_at": expires_at.isoformat(),
            "deleted_at": None,
            "deleted_by": None,
        }
    )
    return token
