from datetime import datetime
from flask import request
from flask_jwt_extended import get_jwt_identity, jwt_required
from app.api import api_bp
from app.models.notification import Notification
from app.utils.pagination import paginate
from app.utils.response import ok


@api_bp.get("/notifications")
@jwt_required()
def list_notifications():
    user_id = get_jwt_identity()
    page = request.args.get("page", 1, type=int)
    page_size = request.args.get("page_size", 20, type=int)
    unread = request.args.get("unread")
    notif_type = request.args.get("type")

    query = Notification.query.filter(
        (Notification.user_id == user_id) | (Notification.user_id.is_(None))
    ).order_by(Notification.created_at.desc())

    if unread == "true":
        query = query.filter(Notification.read_at.is_(None))
    if notif_type:
        query = query.filter(Notification.type == notif_type)

    paged = paginate(query, page, page_size)
    items = [
        {
            "id": n.id,
            "title": n.title,
            "message": n.message,
            "type": n.type,
            "link": n.link,
            "created_at": n.created_at.isoformat(),
            "read_at": n.read_at.isoformat() if n.read_at else None,
        }
        for n in paged["items"]
    ]

    return ok(
        {
            "notifications": items,
            "page": paged["page"],
            "pages": paged["pages"],
            "total": paged["total"],
            "page_size": paged["page_size"],
        }
    )


@api_bp.post("/notifications/mark-read")
@jwt_required()
def mark_notifications_read():
    user_id = get_jwt_identity()
    data = request.json or {}
    ids = data.get("ids", [])
    updated = 0

    query = Notification.query.filter(
        (Notification.user_id == user_id) | (Notification.user_id.is_(None))
    )
    if ids:
        query = query.filter(Notification.id.in_(ids))

    for notification in query.all():
        if not notification.read_at:
            notification.read_at = datetime.utcnow()
            updated += 1

    if updated:
        Notification.query.session.commit()

    return ok({"updated": updated}, "Notifications updated")


@api_bp.post("/notifications/mark-all-read")
@jwt_required()
def mark_all_notifications_read():
    user_id = get_jwt_identity()
    updated = 0
    query = Notification.query.filter(
        (Notification.user_id == user_id) | (Notification.user_id.is_(None))
    ).filter(Notification.read_at.is_(None))

    for notification in query.all():
        notification.read_at = datetime.utcnow()
        updated += 1

    if updated:
        Notification.query.session.commit()

    return ok({"updated": updated}, "All notifications updated")
