from datetime import datetime

from src.core.api_responses import (
    build_success_payload,
    build_error_payload,
)


class TestSuccessPayload:
    """Test successful response payload construction."""

    def test_build_success_payload_with_data(self):
        """Test building success response with data."""
        data = {"id": "123", "name": "test"}
        message = "Success"

        response = build_success_payload(data=data, message=message)

        assert response["message"] == message
        assert response["data"] == data
        assert "timestamp" in response

    def test_build_success_payload_without_data(self):
        """Test building success response without data."""
        message = "Operation successful"

        response = build_success_payload(message=message)

        assert response["message"] == message
        assert response.get("data") is None or response.get("data") == []
        assert "timestamp" in response

    def test_build_success_payload_with_list_data(self):
        """Test building success response with list data."""
        data = [
            {"id": "1", "name": "item1"},
            {"id": "2", "name": "item2"},
        ]
        message = "2 items found"

        response = build_success_payload(data=data, message=message)

        assert isinstance(response["data"], list)
        assert len(response["data"]) == 2


class TestErrorPayload:
    """Test error response payload construction."""

    def test_build_error_payload_basic(self):
        """Test building basic error response."""
        error_code = "NOT_FOUND"
        error_message = "Resource not found"

        response = build_error_payload(
            error_code=error_code,
            error_message=error_message,
        )

        assert response["error"]["code"] == error_code
        assert response["error"]["message"] == error_message
        assert "timestamp" in response

    def test_build_error_payload_with_details(self):
        """Test building error response with details."""
        error_code = "VALIDATION_ERROR"
        error_message = "Invalid input"
        details = {"reason": "Invalid format"}

        response = build_error_payload(
            error_code=error_code,
            error_message=error_message,
            details=details,
        )

        assert response["error"]["code"] == error_code
        assert response["error"]["message"] == error_message


class TestTimestampFormat:
    """Test timestamp formatting in responses."""

    def test_timestamp_is_iso_format(self):
        """Test that timestamp is in ISO format."""
        response = build_success_payload(message="Test")
        timestamp = response["timestamp"]
        datetime.fromisoformat(timestamp)
