import json
import logging

from odoo.http import request

_logger = logging.getLogger(__name__)


def _decode_json_body(self, request_obj=None):
    req = request_obj or request
    if not req.httprequest.data:
        raise ValueError("No data provided")
    raw_data = req.httprequest.data
    if isinstance(raw_data, bytes):
        raw_data = raw_data.decode("utf-8")
    try:
        data = json.loads(raw_data)
    except Exception as e:
        raise ValueError(f"Invalid JSON: {str(e)}") from e
    return data


def _build_group_order_unavailable_response(self, group_order, status=403):
    req = getattr(self, "_request", None) or request
    return req.make_response(
        json.dumps(
            {
                "error": req.env._("Order is not available"),
                "code": "group_order_not_open",
                "order_state": group_order.state if group_order else False,
                "action": "clear_cart",
            }
        ),
        [("Content-Type", "application/json")],
        status=status,
    )
