"""Cart page utilities — serializers and formatters."""
from __future__ import annotations

from typing import Any


def _serialize_order(order: Any) -> dict:
    from shared.infrastructure.urls import market_product_url
    created = order.created_at.strftime("%-d %b %Y, %H:%M") if order.created_at else "\u2014"
    items = []
    if order.items:
        for item in order.items:
            items.append({
                "product_image": item.product_image,
                "product_title": item.product_title or "Unknown product",
                "product_id": item.product_id,
                "product_slug": item.product_slug,
                "product_url": market_product_url(item.product_slug),
                "quantity": item.quantity,
                "unit_price_formatted": f"{item.unit_price or 0:.2f}",
                "currency": item.currency or order.currency or "GBP",
            })
    return {
        "id": order.id,
        "status": order.status or "pending",
        "created_at_formatted": created,
        "description": order.description or "",
        "total_formatted": f"{order.total_amount or 0:.2f}",
        "total_amount": float(order.total_amount or 0),
        "currency": order.currency or "GBP",
        "items": items,
    }


def _serialize_calendar_entry(e: Any) -> dict:
    st = e.state or ""
    ds = e.start_at.strftime("%-d %b %Y, %H:%M") if e.start_at else ""
    if e.end_at:
        ds += f" \u2013 {e.end_at.strftime('%-d %b %Y, %H:%M')}"
    return {"name": e.name, "state": st, "date_str": ds, "cost_formatted": f"{e.cost or 0:.2f}"}
