# SPDX-FileCopyrightText: (c) TagStudio Contributors
# SPDX-License-Identifier: GPL-3.0-only


from pathlib import Path
from tempfile import TemporaryDirectory

import pytest

from tagstudio.core.library.alchemy.enums import BrowsingState
from tagstudio.core.library.alchemy.library import Library
from tagstudio.core.library.alchemy.registries.unlinked_registry import UnlinkedRegistry
from tagstudio.core.utils.types import unwrap

CWD = Path(__file__).parent


# NOTE: Does this test actually work?
@pytest.mark.parametrize("library", [TemporaryDirectory()], indirect=True)
def test_refresh_unlinked_entries(library: Library):
    registry = UnlinkedRegistry(lib=library)

    # touch the file `one/two/bar.md` but in wrong location to simulate a moved file
    (unwrap(library.library_dir) / "bar.md").touch()

    # no files actually exist, so it should return all entries
    assert list(registry.refresh_unlinked_files()) == [0, 1]

    # neither of the library entries exist
    assert len(registry.unlinked_entries) == 2

    # iterate through two files
    assert list(registry.fix_unlinked_entries()) == [0, 1]

    # `bar.md` should be relinked to new correct path
    results = library.search_library(BrowsingState.from_path("bar.md"), page_size=500)
    entries = library.get_entries(results.ids)
    assert entries[0].path == Path("bar.md")
