# /opt/docker/dev/service_finder/backend/app/api/v1/endpoints/notifications.py
import uuid
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, update, desc, func

from app.db.session import get_db
from app.api.deps import get_current_user
from app.models.identity import User
from app.models.system import InternalNotification
from app.schemas.social import NotificationResponse, NotificationUpdate # Feltételezett sémák

router = APIRouter()

@router.get("/my", response_model=List[NotificationResponse])
async def get_my_notifications(
    db: AsyncSession = Depends(get_db), 
    current_user: User = Depends(get_current_user),
    unread_only: bool = False,
    limit: int = Query(50, ge=1, le=100),
    offset: int = 0
):
    """
    Lekéri a bejelentkezett felhasználó értesítéseit. 
    Támogatja a szűrést az olvasatlanokra és a lapozást.
    """
    stmt = (
        select(InternalNotification)
        .where(InternalNotification.user_id == current_user.id)
    )
    
    if unread_only:
        stmt = stmt.where(InternalNotification.is_read == False)
    
    stmt = stmt.order_by(desc(InternalNotification.created_at)).offset(offset).limit(limit)
    
    result = await db.execute(stmt)
    return result.scalars().all()

@router.post("/mark-read")
async def mark_as_read(
    notification_ids: List[uuid.UUID],
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    Egy vagy több értesítés olvasottnak jelölése.
    """
    if not notification_ids:
        raise HTTPException(status_code=400, detail="Nincs megadva azonosító.")

    stmt = (
        update(InternalNotification)
        .where(InternalNotification.id.in_(notification_ids))
        .where(InternalNotification.user_id == current_user.id)
        .values(is_read=True, read_at=func.now())
    )
    
    await db.execute(stmt)
    await db.commit()
    
    return {"status": "success", "marked_count": len(notification_ids)}

@router.post("/mark-all-read")
async def mark_all_read(
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    A felhasználó összes értesítésének olvasottnak jelölése.
    """
    stmt = (
        update(InternalNotification)
        .where(InternalNotification.user_id == current_user.id)
        .where(InternalNotification.is_read == False)
        .values(is_read=True, read_at=func.now())
    )
    
    await db.execute(stmt)
    await db.commit()
    
    return {"status": "success", "message": "Minden értesítés olvasottnak jelölve."}

@router.get("/summary")
async def get_notification_summary(
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    Gyors összesítő a Dashboard-hoz (pl. hány olvasatlan van).
    """
    stmt = (
        select(func.count(InternalNotification.id))
        .where(InternalNotification.user_id == current_user.id)
        .where(InternalNotification.is_read == False)
    )
    
    unread_count = (await db.execute(stmt)).scalar() or 0
    return {"unread_count": unread_count}