from sqlalchemy.orm import Session
from app.models.notification import Notification, Follow


def create_notification(db: Session, user_id: int, actor_id: int | None, notification_type: str, message: str, link: str | None = None):
    notif = Notification(
        user_id=user_id,
        actor_id=actor_id,
        notification_type=notification_type,
        message=message,
        link=link,
    )
    db.add(notif)
    db.commit()
    return notif


def notify_followers(db: Session, target_type: str, target_id: int, actor_id: int, notification_type: str, message: str, link: str | None = None):
    """Send notification to all followers of a target (question, publication, user)."""
    follows = db.query(Follow).filter(
        Follow.target_type == target_type,
        Follow.target_id == target_id,
        Follow.follower_id != actor_id,
    ).all()
    for follow in follows:
        create_notification(db, follow.follower_id, actor_id, notification_type, message, link)
