from fastapi import APIRouter, Cookie, Depends, HTTPException
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, admin: bool = False, db: Session = Depends(get_db)):
    return crud.get_news(place, admin, db)


@router.post('/news', response_model=schemas.News)
async def create_news(news: schemas.NewsBase, connect_id: str = Cookie(...), db: Session = Depends(get_db)):
    user = crud.get_user(connect_id, db)
    if user.admin:
        saved_news = crud.create_news(news, db)
        await manager.broadcast(json.dumps({"type": "news", "comment": saved_news.__dict__}, default=str))
        return saved_news
    else:
        raise HTTPException(status_code=403, detail="Administrator privilege required")


@router.delete('/news/{id}', response_model=None)
async def delete_news(id: int, connect_id: str = Cookie(...), db: Session = Depends(get_db)):
    user = crud.get_user(connect_id, db)
    if user.admin:
        return crud.delete_news(id, db)
    else:
        raise HTTPException(status_code=403, detail="Administrator privilege required")
