# retoor <retoor@molodetz.nl>

from datetime import datetime, timezone
from typing import Optional

from devplacepy.database import get_table


def as_int(value: object, default: int = 0) -> int:
    try:
        return int(value)
    except (TypeError, ValueError):
        return default


def to_unix(iso_value: Optional[str]) -> int:
    if not iso_value:
        return 0
    try:
        moment = datetime.fromisoformat(iso_value)
    except (ValueError, TypeError):
        return 0
    if moment.tzinfo is None:
        moment = moment.replace(tzinfo=timezone.utc)
    return int(moment.timestamp())


def now_unix() -> int:
    return int(datetime.now(timezone.utc).timestamp())


def post_by_id(rant_id: object) -> Optional[dict]:
    identifier = as_int(rant_id)
    if not identifier:
        return None
    return get_table("posts").find_one(id=identifier, deleted_at=None)


def comment_by_id(comment_id: object) -> Optional[dict]:
    identifier = as_int(comment_id)
    if not identifier:
        return None
    return get_table("comments").find_one(id=identifier, deleted_at=None)


def user_by_id(user_id: object) -> Optional[dict]:
    identifier = as_int(user_id)
    if not identifier:
        return None
    return get_table("users").find_one(id=identifier)
