"""方案分类 HTTP 接口。"""

from __future__ import annotations

from flask import request

from dms.api.v1.blueprint import api_v1
from dms.common.errors import InvalidArgumentError
from dms.common.response import success_response
from dms.security.decorators import admin_required, bearer_auth_required
from dms.services.category_service import (
    category_tree,
    create_category,
    delete_category,
    parse_category_id,
    parse_delete_row_version,
    update_category,
)


def _json_body():
    if not request.is_json:
        raise InvalidArgumentError("请求体必须是JSON对象")
    body = request.get_json(silent=True)
    if not isinstance(body, dict):
        raise InvalidArgumentError("请求体必须是JSON对象")
    return body


@api_v1.get("/categories/tree")
@bearer_auth_required
def categories_tree():
    return success_response(
        category_tree(
            keyword=request.args.get("keyword"),
            status=request.args.get("status"),
        )
    )


@api_v1.post("/categories")
@bearer_auth_required
@admin_required
def create_category_route():
    return success_response(create_category(_json_body()), status=201)


@api_v1.put("/categories/<id>")
@bearer_auth_required
@admin_required
def update_category_route(id: str):
    return success_response(
        update_category(parse_category_id(id), _json_body())
    )


@api_v1.delete("/categories/<id>")
@bearer_auth_required
@admin_required
def delete_category_route(id: str):
    return success_response(
        delete_category(
            parse_category_id(id),
            parse_delete_row_version(request.args.get("rowVersion")),
        )
    )
