"""
模型测试
"""
import pytest
from tortoise import Tortoise

from fastapi_tortoise_crud import BaseModel
from fastapi_tortoise_crud.model import fields


# 测试模型
class TestModel(BaseModel):
    name = fields.CharField(max_length=50, description="名称")
    description = fields.TextField(null=True, description="描述")
    
    class Meta:
        table = "test_models"


@pytest.fixture
async def init_db():
    """初始化数据库"""
    await Tortoise.init(
        db_url='sqlite://:memory:',
        modules={'models': ['tests.test_model']}
    )
    await Tortoise.generate_schemas()
    yield
    await Tortoise.close_connections()


@pytest.mark.asyncio
async def test_create_model(init_db):
    """测试创建模型"""
    # 创建记录
    model = await TestModel.create(name="test1", description="desc1")
    assert model.id is not None
    assert model.name == "test1"
    assert model.description == "desc1"
    assert model.status is True
    assert model.version == 1


@pytest.mark.asyncio
async def test_update_model(init_db):
    """测试更新模型"""
    # 创建记录
    model = await TestModel.create(name="test1")
    
    # 更新记录
    await TestModel.update_one(str(model.id), {"name": "test2"})
    
    # 验证更新
    updated = await TestModel.find_one(id=model.id)
    assert updated.name == "test2"
    assert updated.version == 2  # 版本号增加


@pytest.mark.asyncio
async def test_delete_model(init_db):
    """测试删除（禁用）"""
    # 创建记录
    model = await TestModel.create(name="test1")
    
    # 删除（禁用）记录
    await TestModel.delete_one(str(model.id))
    
    # 验证记录已被禁用
    deleted = await TestModel.get_or_none(id=model.id)
    assert deleted.status is False
    
    # 验证查询时会过滤掉已禁用的记录
    result = await TestModel.find_one(id=model.id)
    assert result is None


@pytest.mark.asyncio
async def test_find_with_status(init_db):
    """测试状态过滤"""
    # 创建记录
    model1 = await TestModel.create(name="test1")
    model2 = await TestModel.create(name="test2", status=False)
    
    # 测试默认只查询启用的记录
    results = await TestModel.find_by()
    assert len(results) == 1
    assert results[0].name == "test1"
    
    # 测试查询所有记录
    results = await TestModel.find_by(status=None)
    assert len(results) == 2
    
    # 测试只查询禁用的记录
    results = await TestModel.find_by(status=False)
    assert len(results) == 1
    assert results[0].name == "test2"


@pytest.mark.asyncio
async def test_metadata(init_db):
    """测试元数据"""
    # 创建带元数据的记录
    metadata = {"key1": "value1", "key2": "value2"}
    model = await TestModel.create(
        name="test1",
        metadata=metadata
    )
    
    # 验证元数据
    assert model.metadata == metadata
    
    # 更新元数据
    new_metadata = {"key3": "value3"}
    await TestModel.update_one(str(model.id), {"metadata": new_metadata})
    
    # 验证更新后的元数据
    updated = await TestModel.find_one(id=model.id)
    assert updated.metadata == new_metadata 