"""Aliases API: list, create, remove."""

from quart import Blueprint, jsonify, request

from ..extensions import get_session
from ..services.ml.aliases import AliasService

aliases_bp = Blueprint("aliases", __name__, url_prefix="/api")


@aliases_bp.route("/aliases", methods=["GET"])
async def list_aliases():
    async with get_session() as session:
        rows = await AliasService(session).list_all()
    return jsonify(
        [
            {
                "alias_string": r.alias_string,
                "alias_category": r.alias_category,
                "canonical_tag_id": r.canonical_tag_id,
                "canonical_tag_name": r.canonical_tag_name,
            }
            for r in rows
        ]
    )


@aliases_bp.route("/aliases", methods=["POST"])
async def create_alias():
    body = await request.get_json()
    required = {"alias_string", "alias_category", "canonical_tag_id"}
    if not body or not required.issubset(body):
        return jsonify({"error": f"required: {sorted(required)}"}), 400
    async with get_session() as session:
        await AliasService(session).create(
            body["alias_string"],
            body["alias_category"],
            body["canonical_tag_id"],
        )
        await session.commit()
    return "", 201


@aliases_bp.route(
    "/aliases/<alias_string>/<alias_category>", methods=["DELETE"]
)
async def remove_alias(alias_string: str, alias_category: str):
    async with get_session() as session:
        await AliasService(session).remove(alias_string, alias_category)
        await session.commit()
    return "", 204
