import pytest

pytestmark = pytest.mark.integration


async def _mk_tag(client, name, kind="general"):
    r = await client.post("/api/tags", json={"name": name, "kind": kind})
    return (await r.get_json())["id"]


@pytest.mark.asyncio
async def test_common_tags_rejects_empty_list(client):
    # Spec guard: image_ids must be a non-empty list (the frontend never
    # calls this with an empty selection).
    resp = await client.post("/api/images/common-tags", json={"image_ids": []})
    assert resp.status_code == 400


@pytest.mark.asyncio
async def test_common_tags_requires_list(client):
    resp = await client.post("/api/images/common-tags", json={})
    assert resp.status_code == 400


@pytest.mark.asyncio
async def test_common_tags_ok_shape(client):
    # Unknown image ids are valid input; result is just an empty tag list.
    resp = await client.post(
        "/api/images/common-tags", json={"image_ids": [999999]}
    )
    assert resp.status_code == 200
    assert (await resp.get_json())["tags"] == []


@pytest.mark.asyncio
async def test_bulk_add_route_happy(client):
    tag = await _mk_tag(client, "RouteAdd")
    resp = await client.post(
        "/api/images/bulk/tags",
        json={"image_ids": [1, 2, 3], "tag_id": tag},
    )
    # images 1..3 may not exist; FK means added_count reflects real images.
    assert resp.status_code in (200, 400)


@pytest.mark.asyncio
async def test_bulk_add_rejects_bad_source(client):
    tag = await _mk_tag(client, "RouteAddSrc")
    resp = await client.post(
        "/api/images/bulk/tags",
        json={"image_ids": [1], "tag_id": tag, "source": "evil"},
    )
    assert resp.status_code == 400


@pytest.mark.asyncio
async def test_bulk_add_missing_tag_404(client):
    resp = await client.post(
        "/api/images/bulk/tags",
        json={"image_ids": [1], "tag_id": 999999},
    )
    assert resp.status_code == 404


@pytest.mark.asyncio
async def test_bulk_add_over_cap_400(client):
    tag = await _mk_tag(client, "RouteAddCap")
    resp = await client.post(
        "/api/images/bulk/tags",
        json={"image_ids": list(range(1, 202)), "tag_id": tag},
    )
    assert resp.status_code == 400


@pytest.mark.asyncio
async def test_bulk_remove_route_missing_tag_404(client):
    resp = await client.post(
        "/api/images/bulk/tags/remove",
        json={"image_ids": [1], "tag_id": 999999},
    )
    assert resp.status_code == 404


@pytest.mark.asyncio
async def test_bulk_remove_route_requires_ids(client):
    resp = await client.post(
        "/api/images/bulk/tags/remove", json={"tag_id": 1}
    )
    assert resp.status_code == 400
