"""JSON:API envelope wrapping and unwrapping."""

from __future__ import annotations

from typing import Any


def wrap_create(type_name: str, attributes: dict[str, Any]) -> dict[str, Any]:
    """Wrap attributes in a JSON:API create envelope."""
    return {
        "data": {
            "type": type_name,
            "attributes": attributes,
        }
    }


def wrap_update(type_name: str, id: str, attributes: dict[str, Any]) -> dict[str, Any]:
    """Wrap attributes in a JSON:API update envelope."""
    return {
        "data": {
            "type": type_name,
            "id": id,
            "attributes": attributes,
        }
    }


def unwrap_one(body: dict[str, Any]) -> dict[str, Any]:
    """Extract a single resource's attributes + id from a JSON:API response."""
    data = body["data"]
    result = {"id": data["id"]}
    if "attributes" in data:
        result.update(data["attributes"])
    return result


def unwrap_many(body: dict[str, Any]) -> list[dict[str, Any]]:
    """Extract a list of resources' attributes + id from a JSON:API response."""
    return [{"id": item["id"], **(item.get("attributes", {}))} for item in body["data"]]
