import uuid
from datetime import datetime
from decimal import Decimal
from enum import Enum

from sqlalchemy import (
    DateTime,
    ForeignKey,
    Numeric,
    String,
    UniqueConstraint,
    Uuid,
    func,
)
from sqlalchemy.orm import Mapped, mapped_column

from app.db.session import Base


class GroupOrderSessionStatus(str, Enum):
    OPEN = "open"
    LOCKED = "locked"
    CHECKED_OUT = "checked_out"
    CANCELLED = "cancelled"


class GroupOrderSession(Base):
    """Group ordering — everyone's expected to be together in person
    (see app.api.v1.endpoints.group_orders), adding their own items to
    the host's shared cart via a join_code. True per-guest
    split-payment, not host-pays: locking the session (see
    app.api.v1.endpoints.group_orders.lock_session) splits the cart
    into one real Order per participant who has items, each with their
    own independent gateway checkout (see app.services.payments) for
    just their own items — the host's own resulting Order additionally
    carries the whole group's delivery_fee/service_fee/vat, computed
    on the combined subtotal of everyone's items, not just their own.
    A guest who never pays gets their order cancelled and their items
    copied onto the host's order when the host finalizes (see
    app.api.v1.endpoints.group_orders.finalize_session) — the host
    absorbs the cost of anyone who doesn't pay, same as they'd absorb
    it settling up in person.

    At most one *active* (open or locked) session per cart — checked
    in app.api.v1.endpoints.group_orders.start_session, not enforced
    as a DB constraint (same as most business rules in this codebase).
    Deliberately not a unique constraint on cart_id itself: a Cart row
    is permanent and reused for a customer's entire account lifetime
    (see Cart's own docstring — cleared, not recreated, after every
    checkout), so that would let a host start a group order exactly
    once, ever. A checked-out or cancelled session doesn't count
    against the "at most one active" limit, so the same cart can host
    a new group order next time. A cart already only ever holds one
    branch's items regardless (Cart.branch_id), so every participant's
    items are guaranteed to be from the same restaurant/branch for
    free, with no extra enforcement needed here.

    No scheduled job auto-expires a session at its deadline — there's
    no background-task infrastructure in this codebase yet, and this
    doesn't need one: since everyone's in the same room, "expired" is
    checked lazily wherever it matters (joining, adding an item) rather
    than proactively, and the host manually finalizes when ready
    rather than the session auto-resolving on a timer. deadline is
    nullable — entirely optional; a host who doesn't set one just
    locks/cancels manually when ready.
    """

    __tablename__ = "group_order_sessions"

    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
    )
    host_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True
    )
    # Short and typeable/speakable on purpose (everyone's in the same
    # room reading it off one screen) — unlike
    # app.services.tracking's 32-byte ticket, which nobody ever has to
    # type by hand. See app.services.group_orders.generate_join_code.
    join_code: Mapped[str] = mapped_column(
        String(8), unique=True, index=True, nullable=False
    )
    status: Mapped[str] = mapped_column(
        String(20), nullable=False, default=GroupOrderSessionStatus.OPEN.value
    )
    deadline: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    # Applied per guest, not the host — the host pays for the whole
    # order regardless, so capping their own contribution wouldn't
    # protect anything; this exists to cap what a *guest* can add to
    # someone else's bill. See app.api.v1.endpoints.group_orders.
    per_person_limit: Mapped[Decimal | None] = mapped_column(
        Numeric(10, 2), 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 GroupOrderParticipant(Base):
    """A user who has joined a GroupOrderSession (the host is not a
    row here — they own the session/cart directly via host_id/
    customer_id, never need to "join" their own session). Tracked as
    its own row even before someone adds any items, so the host has a
    real roster to manage (remove someone, see who's in) rather than
    only being able to infer membership from whoever happens to have
    an item in the cart so far."""

    __tablename__ = "group_order_participants"
    __table_args__ = (UniqueConstraint("session_id", "user_id"),)

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
    session_id: Mapped[uuid.UUID] = mapped_column(
        Uuid,
        ForeignKey("group_order_sessions.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    user_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True
    )
    joined_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), nullable=False
    )
