import uuid
from decimal import Decimal

from pydantic import BaseModel, ConfigDict, field_validator


class CartItemAddRequest(BaseModel):
    menu_item_id: uuid.UUID
    # A whole-number count for a normal item, or a fractional amount
    # (e.g. Decimal("0.5")) for a grocery item sold by weight/volume —
    # see app.models.grocery.GroceryItemDetails. Whether a fractional
    # value is actually allowed here depends on the menu item itself,
    # checked in app.api.v1.endpoints.cart, not here.
    quantity: Decimal = Decimal("1")
    option_ids: list[uuid.UUID] = []
    special_instructions: str | None = None
    # Set only by a participant adding to someone else's cart during a
    # GroupOrderSession (see app.models.group_order) — omitted (the
    # default), this is a completely normal solo add to the caller's
    # own cart, unchanged from before this field existed.
    group_session_id: uuid.UUID | None = None

    @field_validator("quantity")
    @classmethod
    def _positive_quantity(cls, v: Decimal) -> Decimal:
        if v <= 0:
            raise ValueError("Quantity must be greater than zero.")
        return v

    @field_validator("special_instructions")
    @classmethod
    def _clean_instructions(cls, v: str | None) -> str | None:
        if v is not None:
            v = v.strip()
            if not v:
                return None
        return v


class CartItemUpdateRequest(BaseModel):
    """Quantity only — changing options/instructions means removing
    the item and adding it again with the new selection, same as most
    delivery apps' own UX for editing a customized item."""

    quantity: Decimal

    @field_validator("quantity")
    @classmethod
    def _positive_quantity(cls, v: Decimal) -> Decimal:
        if v <= 0:
            raise ValueError("Quantity must be greater than zero.")
        return v


class CartItemOptionOut(BaseModel):
    id: uuid.UUID
    menu_item_option_id: uuid.UUID
    name: str
    price_delta: Decimal


class CartItemOut(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    id: uuid.UUID
    menu_item_id: uuid.UUID
    name: str
    unit_price: Decimal
    quantity: Decimal
    unit_of_measure: str | None = None
    options: list[CartItemOptionOut] = []
    special_instructions: str | None = None
    line_total: Decimal
    is_available: bool
    # Always set, even outside a group order (see
    # app.models.cart.CartItem.added_by_user_id) — the UI only needs
    # to actually show this when the cart's part of a
    # GroupOrderSession, but it's here unconditionally rather than
    # threading a "is this a group cart" flag through serialization
    # just to decide whether to include it.
    added_by_user_id: uuid.UUID
    added_by_name: str


class CartOut(BaseModel):
    id: uuid.UUID | None = None
    branch_id: uuid.UUID | None = None
    items: list[CartItemOut] = []
    subtotal: Decimal = Decimal("0.00")
