"""
Tests for schema conversion module
"""

import pytest
from rest_framework import serializers

from drf_mcp.schema import SchemaConverter


class SimpleSerializer(serializers.Serializer):
    """Simple test serializer"""
    name = serializers.CharField(max_length=100)
    email = serializers.EmailField(required=False)
    age = serializers.IntegerField(required=False)


class NestedSerializer(serializers.Serializer):
    """Serializer with nested fields"""
    id = serializers.IntegerField(read_only=True)
    profile = SimpleSerializer()


class TestSchemaConverter:
    """Test schema conversion"""

    def test_converter_initialization(self):
        """Test converter can be initialized"""
        converter = SchemaConverter()
        assert converter is not None

    def test_simple_schema_generation(self):
        """Test simple serializer to schema conversion"""
        converter = SchemaConverter()
        serializer = SimpleSerializer()
        schema = converter.serialize_to_schema(serializer)

        assert schema["type"] == "object"
        assert "name" in schema["properties"]
        assert "email" in schema["properties"]
        assert "age" in schema["properties"]
        assert "name" in schema["required"]  # name is required

    def test_write_schema_excludes_readonly(self):
        """Test write schema handles read-only fields properly"""
        converter = SchemaConverter()
        serializer = NestedSerializer()
        schema = converter.serialize_to_schema(serializer, for_write=True)

        # When writing, we should not include read-only fields in the properties
        # for the write schema, but nested serializer is included
        assert "profile" in schema["properties"]

    def test_field_type_mapping(self):
        """Test field types are correctly mapped"""
        converter = SchemaConverter()
        serializer = SimpleSerializer()
        schema = converter.serialize_to_schema(serializer)

        assert schema["properties"]["name"]["type"] == "string"
        assert schema["properties"]["email"]["type"] == "string"
        assert schema["properties"]["age"]["type"] == "integer"

    def test_clear_cache(self):
        """Test schema cache can be cleared"""
        converter = SchemaConverter()
        serializer = SimpleSerializer()
        converter.serialize_to_schema(serializer)
        converter.clear_cache()
        assert len(converter._schema_cache) == 0
