"""DMS统一响应与序列化工具。"""

from __future__ import annotations

from typing import Any

from flask import Response, jsonify

from dms.common.request_context import REQUEST_ID_HEADER, get_request_id


def success_response(
    data: Any = None,
    *,
    message: str = "success",
    status: int = 200,
) -> tuple[Response, int]:
    request_id = get_request_id()
    response = jsonify(
        {
            "code": "OK",
            "message": message,
            "data": {} if data is None else data,
            "requestId": request_id,
        }
    )
    response.headers[REQUEST_ID_HEADER] = request_id
    return response, status


def error_response(
    code: str,
    message: str,
    *,
    details: Any = None,
    status: int = 500,
) -> tuple[Response, int]:
    request_id = get_request_id()
    response = jsonify(
        {
            "code": code,
            "message": message,
            "details": details,
            "requestId": request_id,
        }
    )
    response.headers[REQUEST_ID_HEADER] = request_id
    return response, status


def serialize_id(value: int | None) -> str | None:
    """将数据库BIGINT安全序列化为十进制字符串。"""
    return None if value is None else str(value)
