"""
Notification REST API Route
GET  /api/notifications           — lấy danh sách (in-app bell)
PATCH /api/notifications/{id}/read — đánh dấu đã đọc
POST  /api/notifications/read-all  — đánh dấu tất cả đã đọc
GET  /api/notifications/unread-count — số chưa đọc (badge)
POST /api/notifications/test       — test fire một notification
"""

import logging
from typing import Optional

from fastapi import APIRouter, HTTPException
from fastapi.responses import JSONResponse

from common.notification.engine import (
    get_notifications, get_unread_count,
    mark_all_read, mark_read, notify, check_negative_spike,
)
from common.notification.events import EventType

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/api/notifications", tags=["Notifications"])


@router.get("")
async def list_notifications(
    limit: int = 50,
    unread_only: bool = False,
):
    """Lấy danh sách notifications cho in-app bell."""
    notifs = get_notifications(limit=limit, unread_only=unread_only)
    return {
        "notifications": notifs,
        "total": len(notifs),
        "unread_count": get_unread_count(),
    }


@router.get("/unread-count")
async def unread_count():
    """Số notification chưa đọc — dùng cho badge."""
    return {"unread_count": get_unread_count()}


@router.patch("/{notification_id}/read")
async def mark_notification_read(notification_id: str):
    """Đánh dấu một notification đã đọc."""
    success = mark_read(notification_id)
    if not success:
        raise HTTPException(status_code=404, detail="Notification not found")
    return {"ok": True, "unread_count": get_unread_count()}


@router.post("/read-all")
async def mark_all_notifications_read():
    """Đánh dấu tất cả notifications đã đọc."""
    count = mark_all_read()
    return {"ok": True, "marked_read": count}


@router.post("/test")
async def fire_test_notification(body: dict):
    """
    Fire một test notification — dùng khi debug/demo.
    Body: { "event_type": "negative_spike", "title": "...", "body": "..." }
    """
    event_type = body.get("event_type", EventType.NEW_SOCIAL_MESSAGE)
    title = body.get("title", "Test Notification")
    msg_body = body.get("body", "Đây là test notification từ Canifa AI Dashboard.")

    notif = notify(event_type=event_type, title=title, body=msg_body)
    return {"ok": True, "notification": notif}


@router.post("/check-spike")
async def check_spike():
    """Manually trigger negative spike check."""
    spiked = check_negative_spike()
    return {"spiked": spiked, "unread_count": get_unread_count()}
