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("/")
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:
        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 = (
        request_data.get("body").get("action").get("selectedItem").get("toolboxId")
    )
    toolkitId = request_data.get("body").get("action").get("selectedItem").get("id")
    quantity = request_data.get("body").get("action").get("quantity")
    price = round(
        request_data.get("body").get("action").get("selectedItem").get("totalCost")
        / 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":
            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


@router.post("/toolkit", summary="Запрос остатка инструмента")
async def toolkit_request(
    request_data: dict = Depends(requestDict),
):
    response = {"status": "error", "data": {}}
    logger.info(f"Получение запроса остатка инструмента")
    # logger.info(request_data)
    toolkitId = request_data.get("body").get("toolkitId")
    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}
    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"],
            }
        else:
            stocksData["toolboxes"][toolboxTitle]["count"] += stock["quantity"]
    response["status"] = "ok"
    response["data"] = stocksData
    logger.info(response)
    return response
