# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========

import os

import pytest
import pytest_asyncio

from mirage.cache.index.config import IndexEntry
from mirage.cache.index.redis import RedisIndexCacheStore

REDIS_URL = os.environ.get("REDIS_URL", "")
pytestmark = pytest.mark.skipif(not REDIS_URL, reason="REDIS_URL not set")


@pytest_asyncio.fixture()
async def store():
    s = RedisIndexCacheStore(ttl=60, url=REDIS_URL, key_prefix="test:order:")
    await s.clear()
    yield s
    await s.clear()
    await s.close()


@pytest.mark.asyncio
async def test_set_dir_preserves_insertion_order(store):
    entries = [
        ("2026-05-03_zebra__id3.gdoc.json",
         IndexEntry(id="3", name="zebra", resource_type="gdocs/file")),
        ("2026-05-02_apple__id2.gdoc.json",
         IndexEntry(id="2", name="apple", resource_type="gdocs/file")),
        ("2026-05-01_mango__id1.gdoc.json",
         IndexEntry(id="1", name="mango", resource_type="gdocs/file")),
    ]
    await store.set_dir("/gdocs/owned", entries)
    result = await store.list_dir("/gdocs/owned")
    assert result.entries == [
        "/gdocs/owned/2026-05-03_zebra__id3.gdoc.json",
        "/gdocs/owned/2026-05-02_apple__id2.gdoc.json",
        "/gdocs/owned/2026-05-01_mango__id1.gdoc.json",
    ]
