from time import time

from fastapi import APIRouter

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

router = APIRouter()


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

    services_kits = await mongo.service_kits_collection.find({}, {
        "_id": False
    }).sort("id", mongo.desc).to_list(None)

    for service_kit in services_kits:
        service_kit["services"] = await mongo.services_collection.find(
            {"id": {"$in": service_kit["servicesIds"]}},
            {"_id": False}
        ).to_list(None)

    return response({
        "servicesKits": services_kits
    }, start_time=start_time)


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

    service_kit = params["data"]
    service_kit["id"] = await mongo.get_next_id(mongo.service_kits_collection)

    await mongo.service_kits_collection.insert_one(service_kit)
    return response({
        "message": "Набор успешно создан!",
        "ok": True
    }, start_time=start_time)


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

    service_kit_id = params["data"]["id"]
    await mongo.service_kits_collection.update_one(
        {"id": service_kit_id},
        {"$set": params["data"]}
    )

    return response({
        "message": "Набор успешно обновлён!",
        "ok": True
    }, start_time=start_time)
