"""Notifications-Router: Persistente Benachrichtigungen (Multi-Tenant)."""
import logging
from fastapi import APIRouter, Depends, Query
from models import NotificationResponse, NotificationMarkReadRequest
from auth import get_current_user
from database import db_dependency
import aiosqlite

logger = logging.getLogger("osint.notifications")

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


@router.get("", response_model=list[NotificationResponse])
async def list_notifications(
    limit: int = Query(default=50, ge=1, le=200),
    current_user: dict = Depends(get_current_user),
    db: aiosqlite.Connection = Depends(db_dependency),
):
    """Eigene Notifications abrufen (neueste zuerst)."""
    cursor = await db.execute(
        "SELECT * FROM notifications WHERE user_id = ? ORDER BY created_at DESC LIMIT ?",
        (current_user["id"], limit),
    )
    rows = await cursor.fetchall()
    return [dict(row) for row in rows]


@router.get("/unread-count")
async def get_unread_count(
    current_user: dict = Depends(get_current_user),
    db: aiosqlite.Connection = Depends(db_dependency),
):
    """Anzahl ungelesener Notifications."""
    cursor = await db.execute(
        "SELECT COUNT(*) as cnt FROM notifications WHERE user_id = ? AND is_read = 0",
        (current_user["id"],),
    )
    row = await cursor.fetchone()
    return {"unread_count": row["cnt"]}


@router.put("/mark-read")
async def mark_notifications_read(
    body: NotificationMarkReadRequest,
    current_user: dict = Depends(get_current_user),
    db: aiosqlite.Connection = Depends(db_dependency),
):
    """Notifications als gelesen markieren (bestimmte IDs oder alle)."""
    if body.notification_ids:
        placeholders = ",".join("?" for _ in body.notification_ids)
        await db.execute(
            f"UPDATE notifications SET is_read = 1 WHERE user_id = ? AND id IN ({placeholders})",
            [current_user["id"]] + body.notification_ids,
        )
    else:
        await db.execute(
            "UPDATE notifications SET is_read = 1 WHERE user_id = ? AND is_read = 0",
            (current_user["id"],),
        )
    await db.commit()
    return {"ok": True}
