from time import time

from fastapi import APIRouter

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

router = APIRouter()


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

    shipping_warehouses = await mongo.shipping_warehouses_collection.find({}, {
        "_id": False
    }).sort("id", mongo.asc).to_list()

    return response({
        "shippingWarehouses": shipping_warehouses
    }, start_time=start_time)


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

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

    try:
        await mongo.shipping_warehouses_collection.insert_one(data)
        return response({
            "message": "Склад отгрузки создан",
            "ok": True
        }, start_time=start_time)
    except Exception as e:
        return response({
            "message": str(e),
            "ok": False
        }, start_time=start_time, code=400)


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

    logger.json(data)

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

        return response({
            "message": "Склад отгрузки обновлен",
            "ok": True
        }, start_time=start_time)
    except Exception as e:
        return response({
            "message": str(e),
            "ok": False
        }, start_time=start_time, code=400)


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

    try:
        await mongo.shipping_warehouses_collection.delete_one({
            "id": shipping_warehouse_id
        })

        return response({
            "message": "Склад отгрузки удален",
            "ok": True
        }, start_time=start_time)
    except Exception as e:
        return response({
            "message": str(e),
            "ok": False
        }, start_time=start_time, code=400)
