"""ReportLayoutSerializer — delegates serialization to get_report_data() and builds error dicts."""

from boh.report.layout import CustomRenderReportResponse, ReportLayoutResponse
from boh.report.serializer import ReportLayoutSerializer


def test_serializes_report_layout_response():
    response = ReportLayoutResponse()
    response.set_report_data([{"id": 1}])

    result = ReportLayoutSerializer("TestReport").serialize(response)

    assert result["data"] == [{"id": 1}]


def test_serializes_custom_render_report_response():
    response = CustomRenderReportResponse()
    response.add_resource("columns", [{"id": "name"}])

    result = ReportLayoutSerializer("TestReport").serialize(response)

    assert result["resources"] == {"columns": [{"id": "name"}]}


def test_serialize_error_includes_report_id_and_message():
    serializer = ReportLayoutSerializer("SalesReport")

    result = serializer.serialize_error(
        input_obj={"store": "S1"},
        exception=ValueError("db error"),
        original_payload={"report-id": "r42"},
    )

    assert result["error"] is True
    assert result["report-id"] == "r42"
    assert "db error" in result["report-error-message"]
    assert "SalesReport" in result["report-error-message"]


def test_serialize_parser_error_excludes_report_id():
    serializer = ReportLayoutSerializer("SalesReport")

    result = serializer.serialize_parser_error(
        data=b"bad bytes",
        exception=ValueError("bad payload"),
    )

    assert result["error"] is True
    assert "report-id" not in result
    assert "bad payload" in result["report-error-message"]
    assert "SalesReport" in result["report-error-message"]


def test_default_processor_serializer_uses_report_layout_serializer(build_handler, message_bus):
    import json
    import logging

    from messagebus import Event

    from boh.report.processor import ReportProcessor
    from boh.report.sender import BaseSender

    response = CustomRenderReportResponse()
    response.set_report_data([{"row": 1}])

    class _Interactor:
        def execute(self, request):
            return response

    processor = ReportProcessor(
        report_name="TestReport",
        parser=lambda data, event_type: data,
        logger=logging.getLogger("test"),
        interactor=_Interactor(),
        sender=BaseSender(),
    )
    build_handler(event_processors={"test.report": processor}).handle_event(
        message_bus, Event("test.report", None, b'{"report-id": "r1"}')
    )

    dispatched = json.loads(message_bus.published_events[0].data)
    assert dispatched["data"]["data"] == [{"row": 1}]
