import pytest

from backend.app.models import TagKind
from backend.app.services.tag_service import TagService

pytestmark = pytest.mark.integration


@pytest.mark.asyncio
async def test_create_list_delete(client, db):
    tag = await TagService(db).find_or_create("Canon", TagKind.character)
    await db.commit()

    resp = await client.post(
        "/api/aliases",
        json={
            "alias_string": "model_name",
            "alias_category": "character",
            "canonical_tag_id": tag.id,
        },
    )
    assert resp.status_code == 201

    resp = await client.get("/api/aliases")
    body = await resp.get_json()
    assert any(
        a["alias_string"] == "model_name"
        and a["canonical_tag_name"] == "Canon"
        for a in body
    )

    resp = await client.delete("/api/aliases/model_name/character")
    assert resp.status_code == 204


@pytest.mark.asyncio
async def test_create_requires_fields(client):
    resp = await client.post("/api/aliases", json={"alias_string": "x"})
    assert resp.status_code == 400


@pytest.mark.asyncio
async def test_list_for_tag_endpoint(client, db):
    tag = await TagService(db).find_or_create("TagSide", TagKind.character)
    await db.commit()
    await client.post(
        "/api/aliases",
        json={
            "alias_string": "ts_key",
            "alias_category": "character",
            "canonical_tag_id": tag.id,
        },
    )

    resp = await client.get(f"/api/tags/{tag.id}/aliases")
    assert resp.status_code == 200
    body = await resp.get_json()
    assert body == [{"alias_string": "ts_key", "alias_category": "character"}]

    assert (await client.get("/api/tags/99999999/aliases")).status_code == 404
