from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from typing import List
import json

from db import schemas, crud
from db.database import get_db
from .websocket import manager


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


@router.get('/{place}/news', response_model=List[schemas.News])
async def get_news(place: str, db: Session = Depends(get_db)):
    return crud.get_news(place, db)


@router.post('/news', response_model=schemas.News)
async def create_news(news: schemas.NewsBase, db: Session = Depends(get_db)):
    saved_news = crud.create_news(news, db)
    await manager.broadcast(json.dumps({"type": "news", "comment": saved_news.__dict__}, default=str))
    return saved_news


@router.delete('/news/{id}', response_model=None)
async def delete_news(id: int, db: Session = Depends(get_db)):
    return crud.delete_news(id, db)
