from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from db.session import get_db
from core.deps import get_current_user, get_current_admin
from domains.notifications.schemas import (
    NotificationResponse, 
    NotificationAction, 
    NotificationCreate
)
from domains.notifications.service import (
    list_my_notifications, 
    respond_to_notification,
    send_public_notification
)
from domains.users.repo import get_all_users

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

@router.get("/", response_model=list[NotificationResponse])
async def my_notifications(
    db: AsyncSession = Depends(get_db),
    user=Depends(get_current_user)
):
    return await list_my_notifications(db, user.id)

@router.post("/{notification_id}/respond", response_model=NotificationResponse)
async def respond_notification(
    notification_id: str,
    payload: NotificationAction,
    db: AsyncSession = Depends(get_db),
    user=Depends(get_current_user)
):
    try:
        return await respond_to_notification(
            db, 
            notification_id, 
            user.id, 
            payload.is_accepted
        )
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )

@router.post("/public")
async def broadcast_notification(
    title: str,
    description: str,
    db: AsyncSession = Depends(get_db),
    admin=Depends(get_current_admin)
):
    users = await get_all_users(db)
    user_ids = [u.id for u in users]
    return await send_public_notification(
        db, 
        title, 
        description, 
        admin.id, 
        user_ids
    )
