from tinydb import Query
from db.db import push_subscriptions_db
from models.push_subscription import PushSubscription


def get_subscriptions_by_user(user_id: str) -> list[PushSubscription]:
    """Return all push subscriptions for a user."""
    Q = Query()
    results = push_subscriptions_db.search(Q.user_id == user_id)
    return [PushSubscription.from_dict(r) for r in results]


def upsert_subscription(user_id: str, endpoint: str, keys: dict) -> PushSubscription:
    """Insert or update a subscription for the given user+endpoint pair."""
    Q = Query()
    existing = push_subscriptions_db.get((Q.user_id == user_id) & (Q.endpoint == endpoint))
    if existing:
        sub = PushSubscription.from_dict(existing)
        sub.keys = keys
        sub.touch()
        push_subscriptions_db.update(sub.to_dict(), (Q.user_id == user_id) & (Q.endpoint == endpoint))
        return sub
    sub = PushSubscription(user_id=user_id, endpoint=endpoint, keys=keys)
    push_subscriptions_db.insert(sub.to_dict())
    return sub


def delete_by_endpoint(user_id: str, endpoint: str) -> int:
    """Remove the subscription with the given endpoint for this user. Returns count removed."""
    Q = Query()
    removed = push_subscriptions_db.remove((Q.user_id == user_id) & (Q.endpoint == endpoint))
    return len(removed)


def delete_subscription_by_id(subscription_id: str) -> None:
    """Remove a subscription by its ID (used when push delivery fails)."""
    Q = Query()
    push_subscriptions_db.remove(Q.id == subscription_id)
