from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

from app.database import get_db
from app.models.user import User
from app.models.notification import Notification, Follow
from app.services.auth import require_user

router = APIRouter(prefix="/api/notifications", tags=["notifications"])


@router.get("")
def list_notifications(
    unread_only: bool = Query(False),
    page: int = Query(1, ge=1),
    per_page: int = Query(20, ge=1, le=100),
    user: User = Depends(require_user),
    db: Session = Depends(get_db),
):
    query = db.query(Notification).filter(Notification.user_id == user.id)
    if unread_only:
        query = query.filter(Notification.is_read == False)
    total = query.count()
    notifications = query.order_by(Notification.created_at.desc()).offset((page - 1) * per_page).limit(per_page).all()
    return {
        "total": total, "unread_count": db.query(Notification).filter(Notification.user_id == user.id, Notification.is_read == False).count(),
        "results": [
            {"id": n.id, "type": n.notification_type, "message": n.message, "link": n.link, "is_read": n.is_read, "created_at": str(n.created_at)}
            for n in notifications
        ],
    }


@router.post("/{notification_id}/read")
def mark_read(notification_id: int, user: User = Depends(require_user), db: Session = Depends(get_db)):
    n = db.query(Notification).filter(Notification.id == notification_id, Notification.user_id == user.id).first()
    if n:
        n.is_read = True
        db.commit()
    return {"message": "Marked as read"}


@router.post("/read-all")
def mark_all_read(user: User = Depends(require_user), db: Session = Depends(get_db)):
    db.query(Notification).filter(Notification.user_id == user.id, Notification.is_read == False).update({"is_read": True})
    db.commit()
    return {"message": "All marked as read"}


@router.post("/follow")
def follow_target(target_type: str = Query(...), target_id: int = Query(...), user: User = Depends(require_user), db: Session = Depends(get_db)):
    existing = db.query(Follow).filter(Follow.follower_id == user.id, Follow.target_type == target_type, Follow.target_id == target_id).first()
    if existing:
        return {"message": "Already following"}
    follow = Follow(follower_id=user.id, target_type=target_type, target_id=target_id)
    db.add(follow)
    db.commit()
    return {"message": "Following"}


@router.post("/unfollow")
def unfollow_target(target_type: str = Query(...), target_id: int = Query(...), user: User = Depends(require_user), db: Session = Depends(get_db)):
    follow = db.query(Follow).filter(Follow.follower_id == user.id, Follow.target_type == target_type, Follow.target_id == target_id).first()
    if follow:
        db.delete(follow)
        db.commit()
    return {"message": "Unfollowed"}
