# retoor <retoor@molodetz.nl>

from .core import _in_clause, db, get_table
from .users import get_users_by_uids
from .pagination import build_pagination


def get_follow_counts(user_uid: str) -> dict:
    if "follows" not in db.tables:
        return {"followers": 0, "following": 0}
    follows = get_table("follows")
    return {
        "followers": follows.count(following_uid=user_uid, deleted_at=None),
        "following": follows.count(follower_uid=user_uid, deleted_at=None),
    }


def get_follow_list(
    user_uid: str, mode: str, page: int = 1, per_page: int = 25
) -> tuple:
    if "follows" not in db.tables:
        return [], build_pagination(page, 0, per_page)
    follows = get_table("follows")
    key = "following_uid" if mode == "followers" else "follower_uid"
    other = "follower_uid" if mode == "followers" else "following_uid"
    total = follows.count(deleted_at=None, **{key: user_uid})
    pagination = build_pagination(page, total, per_page)
    offset = (pagination["page"] - 1) * pagination["per_page"]
    rows = list(
        follows.find(
            order_by=["-created_at"],
            _limit=pagination["per_page"],
            _offset=offset,
            deleted_at=None,
            **{key: user_uid},
        )
    )
    users_map = get_users_by_uids([row[other] for row in rows])
    people = []
    for row in rows:
        person = users_map.get(row[other])
        if person:
            people.append(
                {
                    "uid": person["uid"],
                    "username": person["username"],
                    "bio": (person.get("bio") or "")[:140],
                    "last_seen": person.get("last_seen"),
                    "followed_at": row.get("created_at"),
                }
            )
    return people, pagination


def get_following_among(follower_uid: str, target_uids: list) -> set:
    if not follower_uid or not target_uids or "follows" not in db.tables:
        return set()
    placeholders, params = _in_clause(target_uids)
    params["f"] = follower_uid
    rows = db.query(
        f"SELECT following_uid FROM follows WHERE follower_uid = :f AND following_uid IN ({placeholders}) AND deleted_at IS NULL",
        **params,
    )
    return {row["following_uid"] for row in rows}
