"""Notification helpers — persist + push via Socket.IO."""
from datetime import datetime, timezone
from typing import Optional
from bson import ObjectId
from bson.errors import InvalidId

from deps import get_db


def _oid(s: str):
    try:
        return ObjectId(s)
    except (InvalidId, TypeError):
        return None


async def push(
    user_ids: list[str],
    n_type: str,
    title: str,
    body: str = "",
    link: Optional[str] = None,
    meta: Optional[dict] = None,
):
    """Persist a notification for each user and emit via Socket.IO."""
    db = get_db()
    now = datetime.now(timezone.utc).isoformat()
    docs = []
    for uid in user_ids:
        if not uid:
            continue
        docs.append({
            "user_id": uid,
            "type": n_type,
            "title": title,
            "body": body,
            "link": link,
            "meta": meta or {},
            "read": False,
            "created_at": now,
        })
    if not docs:
        return
    res = await db.notifications.insert_many(docs)
    # emit
    try:
        from socket_server import sio
        for doc, _id in zip(docs, res.inserted_ids):
            payload = {**doc, "id": str(_id)}
            await sio.emit("notification", payload, room=f"user:{doc['user_id']}")
    except Exception:
        pass


def serialize(n: dict) -> dict:
    return {
        "id": str(n["_id"]),
        "type": n.get("type"),
        "title": n.get("title"),
        "body": n.get("body", ""),
        "link": n.get("link"),
        "meta": n.get("meta", {}),
        "read": n.get("read", False),
        "created_at": n.get("created_at"),
    }
