from time import time

from fastapi import APIRouter

from app import mongo
from app.utils.response_util import response

router = APIRouter()


@router.get("/", tags=[""])
async def get():
    start_time = time()

    projects = await mongo.projects_collection.find({}, {
        "_id": False
    }).to_list()

    return response({
        "projects": projects
    }, start_time=start_time)


@router.post("/", tags=[""])
async def post(params: dict):
    start_time = time()
    data = params["project"]

    data["id"] = await mongo.get_next_id(mongo.projects_collection)

    await mongo.projects_collection.insert_one(data)

    return response({
        "message": "Проект создан",
        "ok": True
    }, start_time=start_time)


@router.patch("/", tags=[""])
async def patch(params: dict):
    start_time = time()
    data = params["project"]

    await mongo.projects_collection.update_one({
        "id": data["id"]
    }, {
        "$set": data
    })

    return response({
        "message": "Проект обновлен",
        "ok": True
    }, start_time=start_time)


@router.delete("/{project_id}", tags=[""])
async def delete(project_id: int):
    start_time = time()

    await mongo.projects_collection.delete_one({
        "id": project_id
    })

    return response({
        "message": "Проект удален",
        "ok": True
    }, start_time=start_time)
