# retoor <retoor@molodetz.nl>

from typing import Optional

from devplacepy.database import get_table, get_users_by_uids
from devplacepy.services.devrant.ids import to_unix, now_unix

DEVRANT_TYPE_MAP = {
    "comment": "comment_discuss",
    "reply": "comment_discuss",
    "thread": "comment_discuss",
    "mention": "comment_mention",
    "vote": "rant_vote",
    "follow": "rant_sub",
}

UNREAD_BUCKET = {
    "rant_vote": "upvotes",
    "comment_mention": "mentions",
    "comment_discuss": "comments",
    "rant_sub": "subs",
}

FEED_LIMIT = 50


def build_notif_feed(user: dict) -> dict:
    notifications = list(
        get_table("notifications").find(
            user_uid=user["uid"], order_by=["-created_at"], _limit=FEED_LIMIT
        )
    )
    actor_uids = list(
        {note.get("related_uid") for note in notifications if note.get("related_uid")}
    )
    actors = get_users_by_uids(actor_uids)
    username_map: dict = {}
    items = []
    unread = {
        "all": 0,
        "upvotes": 0,
        "mentions": 0,
        "comments": 0,
        "subs": 0,
        "total": 0,
    }
    for note in notifications:
        dr_type = DEVRANT_TYPE_MAP.get(note.get("type"))
        if not dr_type:
            continue
        actor = actors.get(note.get("related_uid")) or {}
        actor_id = int(actor.get("id") or 0)
        if actor_id:
            username_map[str(actor_id)] = actor.get("username") or ""
        is_read = 1 if note.get("read") else 0
        items.append(
            {
                "type": dr_type,
                "rant_id": 0,
                "comment_id": 0,
                "created_time": to_unix(note.get("created_at")),
                "read": is_read,
                "uid": actor_id,
                "username": actor.get("username") or "",
            }
        )
        if not is_read:
            bucket = UNREAD_BUCKET.get(dr_type)
            if bucket:
                unread[bucket] += 1
            unread["all"] += 1
            unread["total"] += 1
    return {
        "items": items,
        "check_time": now_unix(),
        "username_map": username_map,
        "unread": unread,
        "num_unread": unread["total"],
    }


def clear_notifications(user: dict) -> None:
    notifications = get_table("notifications")
    for note in notifications.find(user_uid=user["uid"], read=False):
        notifications.update({"id": note["id"], "read": True}, ["id"])
