import uuid
from datetime import datetime
from decimal import Decimal
from typing import Literal

from pydantic import BaseModel, ConfigDict

from app.schemas.cart import CartOut


class GroupOrderSessionStartRequest(BaseModel):
    # Both optional — a host who wants a simple, unbounded session can
    # start one with neither set. See GroupOrderSession for why
    # deadline is enforced lazily rather than by a background job.
    deadline: datetime | None = None
    per_person_limit: Decimal | None = None


class GroupOrderLockRequest(BaseModel):
    """Delivery details for the whole group order, collected here
    rather than at session-start — the host may not know these yet
    when they first open the cart for others to add to. No
    payment_method here (unlike CheckoutRequest): every payer gets
    their own gateway checkout, and cash makes no sense for a split
    payment (there's no single moment/person to collect it from) — see
    app.api.v1.endpoints.group_orders.lock_session."""

    delivery_mode: Literal["takeaway", "delivery"]
    delivery_address: str | None = None
    delivery_latitude: float | None = None
    delivery_longitude: float | None = None


class GroupOrderJoinRequest(BaseModel):
    join_code: str


class GroupOrderParticipantOut(BaseModel):
    user_id: uuid.UUID
    name: str
    joined_at: datetime


class GroupOrderSessionOut(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    id: uuid.UUID
    host_id: uuid.UUID
    join_code: str
    status: str
    deadline: datetime | None
    per_person_limit: Decimal | None
    created_at: datetime


class GroupOrderSessionDetailOut(GroupOrderSessionOut):
    """The host sees the same view as everyone else for now — no
    per-participant privacy split yet (see GroupOrderSession's
    docstring); cart.items already carries added_by_user_id/
    added_by_name per line (see app.schemas.cart.CartItemOut) so this
    doubles as the "who's ordered what" breakdown."""

    participants: list[GroupOrderParticipantOut]
    cart: CartOut


class GroupOrderPayerResult(BaseModel):
    """One participant's outcome from locking the session — either a
    real amount + checkout URL (they had items in the cart), or
    amount=0 with checkout_url=None (they joined but never added
    anything, so there's nothing for them to pay)."""

    user_id: uuid.UUID
    name: str
    is_host: bool
    order_id: uuid.UUID
    amount: Decimal
    checkout_url: str | None


class GroupOrderLockResponse(BaseModel):
    session: GroupOrderSessionOut
    payers: list[GroupOrderPayerResult]
