import pytest
from atomsql import Database, Model, StringField, OneToOneField, MultipleObjectsReturned


def test_onetoone_multiple_objects_returned():
    """Test that OneToOneReverseRelation raises MultipleObjectsReturned when multiple objects exist."""

    # Create models for this specific test
    class TestUser(Model):
        name = StringField()

    class TestProfile(Model):
        bio = StringField()
        user = OneToOneField(TestUser)

    # Use an in-memory database
    db = Database("sqlite:///:memory:")

    TestUser.db = db
    TestProfile.db = db

    # Register the models to create tables
    db.register(TestUser)
    db.register(TestProfile)

    # Create user
    user = TestUser(name="Test User")
    user.save(db)

    # Drop the unique constraint by recreating the table without it
    db.backend.execute(f'DROP TABLE "{TestProfile._table_name}"')
    db.backend.execute(
        f'CREATE TABLE "{TestProfile._table_name}" (id INTEGER PRIMARY KEY AUTOINCREMENT, bio TEXT, user_id INTEGER)'
    )
    db.backend.commit()

    # Manually insert multiple profiles with the same user_id
    # This bypasses ORM validation and unique constraints
    db.backend.execute(
        f'INSERT INTO "{TestProfile._table_name}" (bio, user_id) VALUES (?, ?)',
        ["Profile 1", user.id],
    )
    db.backend.execute(
        f'INSERT INTO "{TestProfile._table_name}" (bio, user_id) VALUES (?, ?)',
        ["Profile 2", user.id],
    )
    db.backend.commit()

    # Now accessing the reverse relationship should raise MultipleObjectsReturned
    with pytest.raises(MultipleObjectsReturned) as exc_info:
        _ = user.testprofile  # The reverse relationship name

    assert "get() returned more than one TestProfile" in str(exc_info.value)

    # Cleanup
    db.close()


if __name__ == "__main__":
    test_onetoone_multiple_objects_returned()
    print("MultipleObjectsReturned test passed!")
