from fastapi import APIRouter, Depends
from db.handlers.actions import StocksActions
from db.handlers.categories import CategoryHandler
from db.handlers.records import StocksRecordsHandler
from db.handlers.stock import 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 post_requests(
    request_data: dict = Depends(requestDict),
):
    toolboxId = request_data.get("body").get("toolboxId")
    logger.info(f"Получение инструментов для тулбокса {toolboxId}")
    response = {"status": "error", "data": []}

    stocksData = await StockHandler.getByToolboxId(toolboxId)
    if not stocksData:
        response["status"] = "ok"
        return response
    toolkitsIds = set(stock["toolkit_id"] for stock in stocksData)
    toolkitsData = await ToolkitHandler.getSeveral(list(toolkitsIds))
    if not toolkitsData:
        return response

    categoriesIds = set(toolkit["category_id"] for toolkit in toolkitsData)
    categoriesData = await CategoryHandler.getSeveral(list(categoriesIds))
    if not categoriesData:
        return response

    response["status"] = "ok"
    response["data"] = {
        "stocks": stocksData,
        "toolkits": toolkitsData,
        "categories": categoriesData,
    }
    return response


@router.post("/action", summary="Запрос на перемещение инструмента")
async def post_requests(
    request_data: dict = Depends(requestDict),
):
    action = request_data.get("body").get("action").get("operation")
    logger.info(f"Получение запроса на перемещение ({action}) инструмента")
    userId = request_data.get("body").get("userData").get("id")
    sourceTollboxId = int(
        request_data.get("body").get("action").get("selectedItem").get("toolboxId")
    )
    toolkitId = int(
        request_data.get("body").get("action").get("selectedItem").get("id")
    )
    quantity = request_data.get("body").get("action").get("quantity")
    price = round(
        float(
            request_data.get("body").get("action").get("selectedItem").get("totalCost")
        )
        / int(
            request_data.get("body").get("action").get("selectedItem").get("available")
        ),
        2,
    )
    reason = request_data.get("body").get("action").get("comment")

    resonse = {"status": "error"}

    match action:
        case "writeoff":
            result = await StocksActions.movingRequest(
                "Списание",
                toolkitId,
                sourceTollboxId,
                None,
                quantity,
                reason,
                userId,
                price,
            )
            if result:
                resonse["status"] = "ok"
        case "get":
            logger.info(f"Получение инструмента {toolkitId} из ящика {sourceTollboxId}")
            targetTollboxId = await ToolboxHandler.getIdByOwner(userId)
            result = await StocksActions.takeToolkit(
                sourceTollboxId,
                targetTollboxId,
                toolkitId,
                quantity,
                reason,
                userId,
                price,
            )
            if result:
                resonse["status"] = "ok"
        case "return":
            targetTollboxId = await StocksRecordsHandler.getOriginalToolboxId(
                toolkitId, sourceTollboxId
            )
            if targetTollboxId:
                result = await StocksActions.movingRequest(
                    "Возврат",
                    toolkitId,
                    sourceTollboxId,
                    targetTollboxId,
                    quantity,
                    reason,
                    userId,
                    price,
                )
                if result:
                    resonse["status"] = "ok"
    return resonse
