from datetime import datetime
from app.extensions import db
from app.models.notification import Notification


def create_notification(user_id, title, message, notif_type="info", link=None):
    notification = Notification(
        user_id=user_id,
        title=title,
        message=message,
        type=notif_type,
        link=link,
        created_at=datetime.utcnow(),
    )
    db.session.add(notification)
    db.session.commit()
    return notification


def mark_notifications_read(user_id, ids=None):
    query = Notification.query
    if user_id is not None:
        query = query.filter(Notification.user_id == user_id)
    if ids:
        query = query.filter(Notification.id.in_(ids))
    count = 0
    for notification in query.all():
        if not notification.read_at:
            notification.read_at = datetime.utcnow()
            count += 1
    if count:
        db.session.commit()
    return count
