from fastapi import APIRouter, Depends, Request

from db.handlers.categories import CategoryHandler
from utils import render, requestDict, logger
from .user import router as user
from .stocks import router as stocks


router = APIRouter()

router.include_router(user, prefix="/user", tags=["user"])
router.include_router(stocks, prefix="/stocks", tags=["stocks"])


@router.get("/")
async def main_page(request: Request):
    return await render(request)


@router.post("/")
async def post_requests(
    request_data: dict = Depends(requestDict),
):
    from db.handlers.records import ServiceRecordsHandler, StocksRecordsHandler
    from db.handlers.toolbox import ToolboxHandler
    from db.handlers.toolkit import ToolkitHandler
    from db.handlers.user import UserHandler

    reqData = {
        "tab": request_data.get("body").get("tabId"),
        "userData": request_data.get("body").get("cookiesData").get("userData"),
        "accessData": request_data.get("body").get("cookiesData").get("accessData"),
    }
    resultData = {"status": "error", "data": {}}
    logger.info(f"Получение данных для вкладки {reqData.get('tab')}")
    match reqData.get("tab"):
        case "toolbox":
            if reqData.get("accessData").get("view_all_toolboxes", False):
                toolbox = await ToolboxHandler.getAll()
            else:
                toolbox = await ToolboxHandler.getByOwner(
                    reqData.get("userData").get("id")
                )
            if toolbox:
                resultData["status"] = "ok"
                resultData["data"] = toolbox
        case "requests":
            requests = await StocksRecordsHandler.get(reqData.get("userData").get("id"))
            if isinstance(requests, list):
                resultData["status"] = "ok"
                resultData["data"] = requests
        case "toolkits":
            toolkits = await ToolkitHandler.getAll()
            categories = await CategoryHandler.getAll()
            if toolkits:
                resultData["status"] = "ok"
                resultData["data"] = {
                    "toolkits": toolkits,
                    "categories": categories,
                }
        case "jurnal_toolkits":
            jurnal_toolkits = await StocksRecordsHandler.get()
            if jurnal_toolkits:
                resultData["status"] = "ok"
                resultData["data"] = jurnal_toolkits
        case "jurnal_service":
            jurnal_service = await ServiceRecordsHandler.get()
            if jurnal_service:
                resultData["status"] = "ok"
                resultData["data"] = jurnal_service
        case "users":
            users = await UserHandler.getAll()
            if users:
                for user in users:
                    user.pop("hashed_password")
                resultData["status"] = "ok"
                resultData["data"] = users
        case _:
            pass
    return resultData
