# @File: backend/routers/notifications_extras.py
# @Desc: Lightweight companion endpoints for the notifications feature that
#        live outside the auto-generated entity router at
#        /api/v1/entities/notifications. The frontend admin topbar polls
#        /api/v1/notifications/unread-count on load, so we expose a cheap,
#        per-user unread count here backed by the same notifications table.
import logging

from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession

from core.database import get_db
from dependencies.auth import get_current_user
from models.notifications import Notifications
from schemas.auth import UserResponse

logger = logging.getLogger(__name__)

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


class UnreadCountResponse(BaseModel):
    count: int


@router.get("/unread-count", response_model=UnreadCountResponse)
async def unread_count(
    current_user: UserResponse = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
) -> UnreadCountResponse:
    """Return the number of unread notifications for the current user.

    Never raises — any DB or infrastructure failure is converted into a
    ``count: 0`` response so the admin topbar badge degrades gracefully
    instead of showing a red error banner.
    """
    try:
        stmt = (
            select(func.count())
            .select_from(Notifications)
            .where(Notifications.user_id == str(current_user.id))
            .where(
                (Notifications.read.is_(None)) | (Notifications.read.is_(False))
            )
        )
        result = await db.execute(stmt)
        count = int(result.scalar() or 0)
        return UnreadCountResponse(count=count)
    except HTTPException:
        raise
    except Exception:  # noqa: BLE001 - defensive: never break the topbar badge
        logger.exception("Failed to compute notifications unread count")
        return UnreadCountResponse(count=0)