from fastapi import APIRouter, Depends
from db.handlers.actions import StocksActions
from db.handlers.stock import StockHandler
from db.handlers.toolbox import ToolboxHandler
from utils import requestDict, logger


router = APIRouter()


@router.post("/", summary="Добавление ящика")
async def add_toolbox(reqDict=Depends(requestDict)):
    logger.info(f"Добавление ящика")
    response = {"status": "error"}
    userId = reqDict.get("body").get("userId")
    toolboxData = reqDict.get("body").get("toolboxData")
    result = await ToolboxHandler.add(toolboxData, userId)
    if result:
        response["status"] = "ok"
    return response


@router.put("/", summary="Обновление ящика")
async def update_toolbox(reqDict=Depends(requestDict)):
    toolboxId = reqDict.get("body").get("toolboxId")
    logger.info(f"Обновление ящика #{toolboxId}")
    response = {"status": "error"}
    userId = reqDict.get("body").get("userId")
    toolboxData = reqDict.get("body").get("editToolboxData")
    result = await ToolboxHandler.edit(toolboxId, **toolboxData, user_id=userId)
    if result:
        response["status"] = "ok"
    return response


@router.delete("/", summary="Удаление ящика")
async def delete_toolbox(reqDict=Depends(requestDict)):
    toolboxId = reqDict.get("body").get("toolboxId")
    logger.info(f"Удаление ящика #{toolboxId}")
    response = {"status": "error"}
    stocksData = await StockHandler.getByToolboxId(toolboxId, False)
    if stocksData:
        response["message"] = (
            "Через этот склад были проведены операции, удаление невозможно"
        )
        return response
    userId = reqDict.get("body").get("userId")
    result = await ToolboxHandler.delete(toolboxId, userId)
    if result:
        response["status"] = "ok"
    return response


@router.post("/fill", summary="Заполнение ящика")
async def fill_toolbox(reqDict=Depends(requestDict)):
    logger.info(f"Заполнение ящика")
    logger.info(reqDict.get("body"))
    response = {"status": "error"}
    toolboxId = reqDict.get("body").get("toolboxId")
    userId = reqDict.get("body").get("userId")
    reason = reqDict.get("body").get("reason")
    items = reqDict.get("body").get("items")
    successCount = 0
    for item in items:
        success = await StocksActions.registration(
            item.get("toolkit_id"),
            toolboxId,
            userId,
            item.get("quantity"),
            item.get("price"),
            item.get("placement"),
            reason,
        )
        if success:
            successCount += 1
    if successCount == len(items):
        response["status"] = "ok"
    else:
        response["message"] = (
            f"Оприходовано {successCount} записей из {len(items)}. Проверьте остатки и повторите попытку"
        )
    logger.info(response)
    return response
