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()

    clients = await mongo.clients_collection.find({}, {
        "_id": False
    }).sort("id", mongo.desc).to_list()

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


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

    clients = await mongo.clients_collection.find({
        "name": {
            "$regex": name
        }
    }, {
        "_id": False
    }).sort("id", mongo.asc).to_list()

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


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

    client = await mongo.clients_collection.find_one({
        "id": client_id
    }, {
        "_id": False
    })

    boxes = await mongo.client_boxes_collection.find({
        "clientId": client_id
    }, {
        "_id": False
    }).to_list()
    client["boxes"] = boxes

    pallets = await mongo.client_pallets_collection.find({
        "clientId": client_id
    }, {
        "_id": False
    }).to_list()

    for pallet in pallets:
        pallet["boxes"] = await mongo.client_boxes_collection.find({
            "palletId": pallet["id"]
        }, {
            "_id": False
        }).to_list()

    client["pallets"] = pallets

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


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

    existing_client = await mongo.clients_collection.find_one({"name": data["name"]})
    if existing_client:
        return response({
            "message": f"Клиент с именем '{data['name']}' уже существует",
            "ok": False
        }, start_time=start_time)

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

    return response({
        "message": "Клиент создан",
        "ok": True
    }, start_time=start_time)


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

    logger.json(data)

    try:
        await mongo.clients_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()
    client_id = params["clientId"]

    try:
        await mongo.clients_collection.delete_one({
            "id": client_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)
