from ims_mcp.clients.document import DocumentClient


class _Doc:
    def __init__(self, doc_id: str, name: str):
        self.id = doc_id
        self.name = name
        self.updated = None

    def update(self, payload: dict):
        self.updated = payload
        return self


class _Dataset:
    def __init__(self, pages: list[list[_Doc]]):
        self._pages = pages
        self.list_calls = []
        self.deleted_ids = []
        self.uploaded = []

    def list_documents(self, **kwargs):
        # This test protects against regressions to list_documents(name=...),
        # which can raise ownership errors for unknown names.
        if kwargs.get("name") is not None:
            raise AssertionError("list_documents(name=...) must not be used in upsert")
        self.list_calls.append(kwargs)
        page = kwargs.get("page", 1)
        if page <= len(self._pages):
            return self._pages[page - 1]
        return []

    def delete_documents(self, ids):
        self.deleted_ids.extend(ids)

    def upload_documents(self, document_list):
        self.uploaded.extend(document_list)
        display_name = document_list[0]["display_name"]
        return [_Doc("new-doc", display_name)]


def test_upsert_doc_replaces_existing_with_dataset_scoped_scan():
    dataset = _Dataset(
        pages=[
            [_Doc("d1", "OTHER.md"), _Doc("d2", "VERIFY-TEST.md")],
            [],
        ]
    )
    client = DocumentClient()

    upserted = client.upsert_doc(
        dataset=dataset,
        name="VERIFY-TEST.md",
        content=b"new content",
        meta_fields={"tags": ["test"]},
    )

    assert dataset.deleted_ids == ["d2"]
    assert dataset.uploaded[0]["display_name"] == "VERIFY-TEST.md"
    assert upserted.id == "new-doc"
    assert upserted.updated == {"meta_fields": {"tags": ["test"]}}


def test_upsert_doc_when_no_existing_uploads_without_delete():
    dataset = _Dataset(pages=[[_Doc("d1", "OTHER.md")], []])
    client = DocumentClient()

    upserted = client.upsert_doc(
        dataset=dataset,
        name="VERIFY-TEST.md",
        content=b"content",
        meta_fields=None,
    )

    assert dataset.deleted_ids == []
    assert dataset.uploaded[0]["display_name"] == "VERIFY-TEST.md"
    assert upserted.id == "new-doc"
