from __future__ import annotations

import pytest

from sync_state_machine.common.collection import DataCollection
from tests.fixtures.mock_domain import build_project_node, build_contract_node, register_test_domain


@pytest.mark.asyncio
async def test_collection_filter_by_project_ids() -> None:
    register_test_domain()

    collection = DataCollection("local")
    await collection.add(build_project_node("p1_node", "p1", name="P1", code="P1"))
    await collection.add(build_project_node("p2_node", "p2", name="P2", code="P2"))
    await collection.add(build_contract_node("c1", "c1", name="C1", code="C1", project_ref="p1"))
    await collection.add(build_contract_node("c2", "c2", name="C2", code="C2", project_ref="p2"))

    c1 = collection.get("c1")
    c2 = collection.get("c2")
    assert c1 is not None and c1.get_data() is not None
    assert c2 is not None and c2.get_data() is not None
    c1_data = c1.get_data() or {}
    c2_data = c2.get_data() or {}
    c1_data["project_id"] = "p1"
    c2_data["project_id"] = "p2"
    c1.set_data(c1_data, validate=False)
    c2.set_data(c2_data, validate=False)

    deleted = await collection.filter_by_project_ids(["p1"])

    assert deleted == 1
    assert collection.get("p1_node") is not None
    assert collection.get("c1") is not None
    assert collection.get("p2_node") is not None
    assert collection.get("c2") is None
