from typing import Optional


def get_test_record(rdm, testutils):
    """
    If no testing record exists yet, create fresh and return id.

    If testing record exists, return id of (draft of) latest version.
    If tsuf is passed, will append the string to the description for logging.
    If publish is passed, the draft is published, so it returns just a record id.

    This is used to work on the same record chain while testing the API, avoiding
    spamming the Instance with a lot of testing records per run of the test suite.
    """
    rec_id = None

    def _get_test_record(tsuf: Optional[str] = "", publish=False):
        nonlocal rec_id
        if rec_id is None:
            drft = rdm.draft.create(metadata=testutils.default_bib_metadata())
            drft.files.enabled = False
            drft.metadata.description = ""
            if tsuf:
                drft.metadata.description += f"{tsuf}<br>\n"

            rdm.draft.update(drft)
            if publish:
                rdm.draft.publish(drft.id)
            rec_id = drft.id
            return rec_id
        else:
            drft = rdm.draft.from_record(rdm.record.latest_version(rec_id).id)
            if tsuf:
                drft.metadata.description += f"{tsuf}<br>\n"

            drft = rdm.draft.update(drft)
            if publish:
                rdm.draft.publish(drft.id)
            return drft.id

    yield _get_test_record