"""Unit tests: APIEnvelope and .value property."""

import pytest

from seaart._internal._schemas.envelope import APIEnvelope, Status
from seaart.exceptions import MissingDataError


class TestStatus:
    def test_defaults(self) -> None:
        s = Status()
        assert s.code is None
        assert s.msg == ""
        assert s.request_id is None

    def test_extra_fields_ignored(self) -> None:
        s = Status.model_validate(
            {"code": 10000, "msg": "ok", "request_id": "r1", "extra_field": 42}
        )
        assert s.code == 10000
        assert not hasattr(s, "extra_field")


class TestAPIEnvelope:
    def test_value_returns_data(self) -> None:
        env = APIEnvelope[dict[str, str]].model_validate(
            {"status": {"code": 10000, "msg": "ok"}, "data": {"id": "abc"}}
        )
        assert env.value == {"id": "abc"}

    def test_value_raises_when_none(self) -> None:
        env = APIEnvelope[dict[str, str]].model_validate(
            {"status": {"code": 10000, "msg": "ok"}, "data": None}
        )
        with pytest.raises(MissingDataError):
            _ = env.value

    def test_value_raises_when_data_missing(self) -> None:
        env = APIEnvelope[dict[str, str]].model_validate(
            {"status": {"code": 10000, "msg": "ok"}}
        )
        with pytest.raises(MissingDataError):
            _ = env.value

    def test_data_attribute_is_none(self) -> None:
        env = APIEnvelope[dict[str, str]].model_validate(
            {"status": {"code": 10000, "msg": "ok"}, "data": None}
        )
        assert env.data is None

    def test_status_parsing(self) -> None:
        env = APIEnvelope[dict[str, str]].model_validate(
            {"status": {"code": 70002, "msg": "limit", "request_id": "r42"}}
        )
        assert env.status.code == 70002
        assert env.status.msg == "limit"
        assert env.status.request_id == "r42"
