from quart import Blueprint, jsonify, request

from scribe.auth import get_current_user_id, login_required
from scribe.services.notifications import (
    list_in_app_notifications,
    mark_all_notifications_read,
    mark_notification_read,
    unread_notification_count,
)

notifications_bp = Blueprint("notifications", __name__, url_prefix="/api/notifications")


@notifications_bp.route("", methods=["GET"])
@login_required
async def list_notifications():
    uid = get_current_user_id()
    all_flag = request.args.get("all", "false").lower() == "true"
    items = await list_in_app_notifications(uid, unread_only=not all_flag)
    return jsonify({"notifications": items})


@notifications_bp.route("/count", methods=["GET"])
@login_required
async def get_count():
    uid = get_current_user_id()
    return jsonify({"count": await unread_notification_count(uid)})


@notifications_bp.route("/<int:notif_id>/read", methods=["POST"])
@login_required
async def mark_read(notif_id: int):
    uid = get_current_user_id()
    if not await mark_notification_read(uid, notif_id):
        return jsonify({"error": "Not found"}), 404
    return jsonify({"status": "ok"})


@notifications_bp.route("/read-all", methods=["POST"])
@login_required
async def mark_all_read():
    uid = get_current_user_id()
    count = await mark_all_notifications_read(uid)
    return jsonify({"status": "ok", "marked": count})
