from __future__ import annotations

import pytest

from sync_state_machine.common.collection import DataCollection
from sync_state_machine.domain.project.api_handler import ProjectApiHandler


class _FakeProjectResponse:
    def __init__(self, project_id: str):
        self.id = project_id

    def model_dump(self) -> dict[str, str]:
        return {"id": self.id, "name": f"project-{self.id}"}


@pytest.mark.asyncio
async def test_project_handler_purge_project_data_requires_data_id_filter() -> None:
    handler = ProjectApiHandler()
    handler.set_handler_config({"purge_project_data": True})

    with pytest.raises(ValueError, match="requires non-empty data_id_filter"):
        await handler.load()


@pytest.mark.asyncio
async def test_project_handler_purge_project_data_calls_remote_endpoint(monkeypatch: pytest.MonkeyPatch) -> None:
    handler = ProjectApiHandler()
    handler.set_handler_config(
        {
            "purge_project_data": True,
            "data_id_filter": ["project-1"],
        }
    )
    handler.api_client = object()
    handler.set_collection(DataCollection("remote"))

    purged: list[str] = []

    async def fake_purge(client, project_id: str):
        purged.append(project_id)
        return {"project_id": project_id}

    async def fake_get_project(client, project_id: str):
        return _FakeProjectResponse(project_id)

    async def fake_get_all_info(cls, client, project_id: str):
        return {}

    monkeypatch.setattr("sync_state_machine.domain.project.api_handler.api_purge_project_data", fake_purge)
    monkeypatch.setattr("sync_state_machine.domain.project.api_handler.api_get_project", fake_get_project)
    monkeypatch.setattr(ProjectApiHandler, "get_all_info", classmethod(fake_get_all_info))

    nodes = await handler.load()

    assert purged == ["project-1"]
    assert [node.data_id for node in nodes] == ["project-1"]