from fastapi import APIRouter, Depends
from db.handlers.categories import CategoryHandler
from db.handlers.stock import PlacementHandler, StockHandler
from db.handlers.toolbox import ToolboxHandler
from db.handlers.toolkit import ToolkitHandler
from utils import requestDict, logger


router = APIRouter()


@router.post("/", summary="Запрос остатка инструмента")
async def toolkit_request(
    request_data: dict = Depends(requestDict),
):
    response = {"status": "error", "data": {}}
    toolkitId = request_data.get("body").get("toolkitId")
    logger.info(f"Получение запроса остатка инструмента #{toolkitId}")
    # logger.info(request_data)
    stocks = await StockHandler.getByToolkitId(toolkitId)
    if not stocks:
        return response
    userId = request_data.get("body").get("userId")
    allToolboxes = request_data.get("body").get("allToolboxes")
    toolboxes = (
        await ToolboxHandler.getByOwner(userId)
        if not allToolboxes
        else await ToolboxHandler.getAll()
    )
    if not toolboxes:
        return response
    toolboxesTitles = {toolbox["id"]: toolbox["title"] for toolbox in toolboxes}
    toolboxesOwners = {toolbox["id"]: toolbox["owner_id"] for toolbox in toolboxes}
    stocksData = {"count": 0, "toolboxes": {}}
    for stock in stocks:
        toolboxTitle = toolboxesTitles.get(stock["toolbox_id"], None)
        if not toolboxTitle:
            continue
        stocksData["count"] += stock["quantity"]
        if toolboxTitle not in stocksData["toolboxes"]:
            stocksData["toolboxes"][toolboxTitle] = {
                "count": stock["quantity"],
                "placement": stock["placement"],
            }
            if not toolboxesOwners.get(stock["toolbox_id"]):
                stocksData["toolboxes"][toolboxTitle]["id"] = stock["toolbox_id"]
                stocksData["toolboxes"][toolboxTitle]["totalCost"] = (
                    stock["price"] * stock["quantity"]
                )
        else:
            stocksData["toolboxes"][toolboxTitle]["count"] += stock["quantity"]
            if not toolboxesOwners.get(stock["toolbox_id"]):
                stocksData["toolboxes"][toolboxTitle]["totalCost"] += (
                    stock["price"] * stock["quantity"]
                )
    response["status"] = "ok"
    response["data"] = stocksData
    return response


@router.post("/fill_prepare", summary="Подготовка заполнения ящика")
async def fill_toolbox():
    logger.info(f"Подготовка заполнения ящика")
    response = {"status": "error"}
    toolkits = await ToolkitHandler.getAll()
    categories = await CategoryHandler.getAll()
    placements = await PlacementHandler.getAll()
    if toolkits and categories:
        response["status"] = "ok"
        response["data"] = {
            "toolkits": sorted(toolkits, key=lambda toolkit: toolkit["title"]),
            "categories": sorted(categories, key=lambda category: category["title"]),
            "placements": [placement.toDict() for placement in placements],
        }
    return response
