import uuid
from datetime import datetime
from decimal import Decimal

from sqlalchemy import (
    DateTime,
    ForeignKey,
    Numeric,
    String,
    UniqueConstraint,
    Uuid,
    func,
)
from sqlalchemy.orm import Mapped, mapped_column

from app.db.session import Base


class Cart(Base):
    """A customer's in-progress order, before checkout. One cart per
    customer (unique on customer_id) — adding an item to an empty cart
    sets branch_id; every item after that must belong to the same
    branch (see app.api.v1.endpoints.cart), matching how every food
    delivery app works: you can't check out items from two restaurants
    at once. Hard-deleted (no deleted_at) — it's ephemeral pre-purchase
    state, not a record that needs to survive; checkout converts it
    into an Order (which does survive) and clears the cart."""

    __tablename__ = "carts"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
    customer_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("users.id", ondelete="CASCADE"), unique=True, nullable=False
    )
    branch_id: Mapped[uuid.UUID | None] = mapped_column(
        Uuid, ForeignKey("branches.id", ondelete="CASCADE"), nullable=True
    )

    created_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), nullable=False
    )
    updated_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), onupdate=func.now(), nullable=False
    )


class CartItem(Base):
    """One menu item + quantity within a cart, plus whatever options
    were selected on it (see CartItemOption) and a free-text note for
    anything not covered by those options (e.g. "no onions") — the
    options drive price, the note never does.

    No longer unique on (cart_id, menu_item_id): two cart items can
    both be "Beef Burger" with different options/notes (e.g. one with
    extra cheese, one without) and must stay separate rows. The
    add-item endpoint only merges quantity when menu_item_id, the
    selected options, and the note all match exactly — see
    app.api.v1.endpoints.cart.

    No price stored here on purpose: the cart always shows the
    *current* menu price; only Order/OrderItem snapshot a price, at
    the moment of checkout, when it actually needs to stop changing.

    added_by_user_id is always set, even outside a group order — it's
    the cart owner themselves for a normal solo cart, and whichever
    participant actually added it during a GroupOrderSession (see
    app.models.group_order). Kept populated unconditionally rather
    than only under group ordering so there's one consistent field to
    read, not two different code paths depending on cart type.
    """

    __tablename__ = "cart_items"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
    cart_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("carts.id", ondelete="CASCADE"), nullable=False, index=True
    )
    menu_item_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("menu_items.id", ondelete="CASCADE"), nullable=False
    )
    added_by_user_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("users.id", ondelete="CASCADE"), nullable=False
    )
    # Numeric, not Integer: a grocery item sold by weight/volume (see
    # app.models.grocery.GroceryItemDetails) can have a fractional
    # quantity, e.g. 0.5 kg. Every other item is still required to be a
    # whole number — enforced in app.api.v1.endpoints.cart, not here,
    # same as every other business rule in this codebase.
    quantity: Mapped[Decimal] = mapped_column(
        Numeric(10, 3), nullable=False, default=Decimal("1")
    )
    special_instructions: Mapped[str | None] = mapped_column(String(500), nullable=True)

    created_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), nullable=False
    )
    updated_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), onupdate=func.now(), nullable=False
    )


class CartItemOption(Base):
    """One selected MenuItemOption on a cart item. Unique on
    (cart_item_id, menu_item_option_id) — selecting the same option
    twice is a no-op, not two rows."""

    __tablename__ = "cart_item_options"
    __table_args__ = (UniqueConstraint("cart_item_id", "menu_item_option_id"),)

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
    cart_item_id: Mapped[uuid.UUID] = mapped_column(
        Uuid,
        ForeignKey("cart_items.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    menu_item_option_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("menu_item_options.id", ondelete="CASCADE"), nullable=False
    )

    created_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), nullable=False
    )
