import pytest

from backend.app.models import ImageRecord
from backend.app.services.showcase_service import ShowcaseService

pytestmark = pytest.mark.integration


async def _seed(db, n):
    for i in range(n):
        db.add(ImageRecord(
            path=f"/images/s/{i}.jpg", sha256=f"s{i:063d}",
            size_bytes=1, mime="image/jpeg", width=100, height=200,
            origin="imported_filesystem", integrity_status="unknown",
        ))
    await db.flush()
    await db.commit()


@pytest.mark.asyncio
async def test_random_sample_returns_items_with_shape(db):
    await _seed(db, 20)
    svc = ShowcaseService(db)
    items = await svc.random_sample(limit=5)
    assert 1 <= len(items) <= 5
    first = items[0]
    assert set(first.keys()) == {
        "id", "sha256", "mime", "width", "height", "thumbnail_url"
    }
    assert first["thumbnail_url"].startswith("/images/thumbs/")


@pytest.mark.asyncio
async def test_random_sample_empty_table_returns_empty(db):
    svc = ShowcaseService(db)
    assert await svc.random_sample(limit=5) == []


@pytest.mark.asyncio
async def test_random_sample_rejects_bad_limit(db):
    svc = ShowcaseService(db)
    with pytest.raises(ValueError):
        await svc.random_sample(limit=0)
    with pytest.raises(ValueError):
        await svc.random_sample(limit=201)
