import uuid
from datetime import datetime
from decimal import Decimal
from enum import Enum

from sqlalchemy import DateTime, Float, ForeignKey, Numeric, String, Uuid, func
from sqlalchemy.orm import Mapped, mapped_column

from app.db.session import Base


class OrderStatus(str, Enum):
    PENDING_PAYMENT = "pending_payment"
    CONFIRMED = "confirmed"
    PREPARING = "preparing"
    READY = "ready"
    COMPLETED = "completed"
    CANCELLED = "cancelled"


class PaymentStatus(str, Enum):
    PENDING = "pending"
    PAID = "paid"
    FAILED = "failed"
    # Set when a paid Chapa order is cancelled (see
    # app.api.v1.endpoints.orders._cancel_order) — flags it for an
    # admin to actually process the refund outside this system (bank
    # transfer, Chapa dashboard, etc; Chapa's API does have a real
    # refund endpoint, but this codebase deliberately doesn't call it
    # automatically yet). REFUNDED is set once
    # app.api.v1.endpoints.orders.mark_order_refunded confirms that
    # happened. A cash order never reaches either value: cash is only
    # ever collected on delivery (see courier.mark_delivered), and an
    # order that's already been delivered can't be cancelled.
    REFUND_PENDING = "refund_pending"
    REFUNDED = "refunded"


class DeliveryMode(str, Enum):
    TAKEAWAY = "takeaway"
    DELIVERY = "delivery"


class Order(Base):
    """A placed order — created from a Cart at checkout (see
    app.api.v1.endpoints.orders.checkout), which snapshots each
    CartItem into an OrderItem and clears the cart. Never soft- or
    hard-deleted: it's a financial/audit record, not content — once
    placed, it only ever moves through `status`, never disappears.

    status and payment_status are deliberately separate fields (the
    legacy schema had three overlapping status columns — status /
    paymentstatus / deliverystatus — that were confusing together).
    status won't advance past PENDING_PAYMENT to CONFIRMED until
    payment_status is PAID — enforced in the endpoint, not the DB,
    same as every other business rule in this codebase.

    Pricing breakdown (see app.services.pricing for the formulas):
    total = subtotal + delivery_fee + vat + service_fee - discount_amount.
    delivery_fee is distance-based (branch to delivery_latitude/
    longitude) and zero for takeaway orders, which is also why those
    two columns are nullable — no coordinates are collected for
    takeaway. service_fee and vat apply to every order regardless of
    delivery_mode. discount_amount defaults to 0.00 (no promo code
    used) and is computed off subtotal at checkout time, then applied
    last against the fully-computed total — see
    app.services.promo.validate_promo_code and
    app.api.v1.endpoints.orders.checkout. promo_code_id records which
    code produced it, for the redemption record/audit trail (see
    app.models.promo_code.PromoCodeRedemption); it does NOT get
    re-validated on every read — discount_amount is the frozen,
    already-applied snapshot.
    """

    __tablename__ = "orders"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
    customer_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("users.id"), nullable=False, index=True
    )
    branch_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("branches.id"), nullable=False, index=True
    )
    # Set only when this order came out of locking a GroupOrderSession
    # (see app.models.group_order) — every order sharing the same
    # session_id is part of one physical delivery, even though each
    # participant paid independently. Never set for an ordinary solo
    # checkout. ondelete SET NULL, not CASCADE: the order itself is a
    # financial record that must survive regardless of what happens to
    # the (ephemeral, pre-purchase) session that produced it.
    group_order_session_id: Mapped[uuid.UUID | None] = mapped_column(
        Uuid,
        ForeignKey("group_order_sessions.id", ondelete="SET NULL"),
        nullable=True,
        index=True,
    )

    status: Mapped[str] = mapped_column(
        String(20), nullable=False, default=OrderStatus.PENDING_PAYMENT.value
    )
    delivery_mode: Mapped[str] = mapped_column(String(20), nullable=False)
    delivery_address: Mapped[str | None] = mapped_column(String(255), nullable=True)
    delivery_latitude: Mapped[float | None] = mapped_column(Float, nullable=True)
    delivery_longitude: Mapped[float | None] = mapped_column(Float, nullable=True)
    # "Order for a Friend" — both set together or not at all (enforced
    # in app.schemas.order.CheckoutRequest, not here, same as every
    # other business rule in this codebase). When set, delivery_address
    # /latitude/longitude above are the *recipient's* address, not the
    # customer's own — this is who the courier actually hands the order
    # to, and who app.services.order_notifications.notify_order_confirmed
    # sends a "your order is on its way" SMS to, separately from the
    # customer's own (paying) account notifications.
    recipient_name: Mapped[str | None] = mapped_column(String(100), nullable=True)
    recipient_phone: Mapped[str | None] = mapped_column(String(20), nullable=True)

    subtotal: Mapped[Decimal] = mapped_column(Numeric(10, 2), nullable=False)
    delivery_fee: Mapped[Decimal] = mapped_column(
        Numeric(10, 2), nullable=False, default=Decimal("0.00")
    )
    service_fee: Mapped[Decimal] = mapped_column(
        Numeric(10, 2), nullable=False, default=Decimal("0.00")
    )
    vat: Mapped[Decimal] = mapped_column(
        Numeric(10, 2), nullable=False, default=Decimal("0.00")
    )
    discount_amount: Mapped[Decimal] = mapped_column(
        Numeric(10, 2), nullable=False, default=Decimal("0.00")
    )
    promo_code_id: Mapped[uuid.UUID | None] = mapped_column(
        Uuid, ForeignKey("promo_codes.id"), nullable=True
    )
    total: Mapped[Decimal] = mapped_column(Numeric(10, 2), nullable=False)

    # Payment fields live directly on Order, same as the legacy schema
    # — there's only ever one payment per order (no partial payments/
    # retries-as-separate-rows in this version), so a separate Payment
    # table would just be a 1:1 join for no benefit. tx_ref/
    # chapa_checkout_url are named for Chapa specifically (the only
    # gateway integrated so far — see app.services.payments) but hold
    # whichever provider's own reference/checkout URL once more than
    # one is wired in; not renamed yet since that'd be a breaking
    # change to an already-shipped API field, not a chapa.py-only
    # rename.
    payment_status: Mapped[str] = mapped_column(
        String(20), nullable=False, default=PaymentStatus.PENDING.value
    )
    tx_ref: Mapped[str] = mapped_column(
        String(100), unique=True, index=True, nullable=False
    )
    chapa_checkout_url: Mapped[str | None] = mapped_column(String(500), nullable=True)
    payment_method: Mapped[str | None] = mapped_column(String(50), 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 OrderItem(Base):
    """One line item on an order. name_snapshot/unit_price_snapshot
    are copied from the MenuItem at checkout time and never updated
    again — an order must keep showing what was actually bought and
    paid for, immune to the merchant later renaming or repricing
    that menu item. unit_price_snapshot is the base item price only;
    selected options are itemized separately in OrderItemOption and
    folded into line_total. special_instructions is copied verbatim
    from the CartItem it came from.

    added_by_user_id mirrors CartItem.added_by_user_id — always set
    (the ordering customer themselves for a normal solo order),
    snapshotted at checkout so it survives the cart being cleared.
    Matters most for a group order (see app.models.group_order): if a
    guest never pays and app.api.v1.endpoints.group_orders.
    finalize_session copies their items onto the host's order, this is
    what still shows the host who actually picked each item, even
    though the host ends up paying for it."""

    __tablename__ = "order_items"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
    order_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("orders.id", ondelete="CASCADE"), nullable=False, index=True
    )
    menu_item_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("menu_items.id"), nullable=False
    )
    added_by_user_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("users.id", ondelete="CASCADE"), nullable=False
    )
    name_snapshot: Mapped[str] = mapped_column(String(150), nullable=False)
    unit_price_snapshot: Mapped[Decimal] = mapped_column(Numeric(10, 2), nullable=False)
    # Numeric, not Integer — same reasoning as app.models.cart.CartItem
    # .quantity: a grocery item sold by weight/volume can be fractional.
    quantity: Mapped[Decimal] = mapped_column(Numeric(10, 3), nullable=False)
    line_total: Mapped[Decimal] = mapped_column(Numeric(10, 2), nullable=False)
    special_instructions: Mapped[str | None] = mapped_column(String(500), nullable=True)

    created_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), nullable=False
    )


class OrderItemOption(Base):
    """A snapshotted selected option on an order item — name and
    price_delta copied from MenuItemOption at checkout time, same
    reasoning as OrderItem's own snapshot fields: a later price change
    to "Extra Cheese" must never rewrite a past order.

    menu_item_option_id is a live reference alongside that snapshot —
    same dual pattern as OrderItem.menu_item_id next to its own
    name/price snapshot — so a feature like
    app.api.v1.endpoints.orders.reorder_order can re-resolve whether
    this exact option still exists/is available, without trying to
    match it back up by name (fragile: a renamed or since-recreated
    option would silently mismatch). Nullable because a pre-existing
    order (from before this column existed) has no live option to
    point to, and reorder just treats those as un-resolvable and drops
    them the same way it does a genuinely deleted option."""

    __tablename__ = "order_item_options"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
    order_item_id: Mapped[uuid.UUID] = mapped_column(
        Uuid,
        ForeignKey("order_items.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    menu_item_option_id: Mapped[uuid.UUID | None] = mapped_column(
        Uuid, ForeignKey("menu_item_options.id", ondelete="SET NULL"), nullable=True
    )
    name_snapshot: Mapped[str] = mapped_column(String(100), nullable=False)
    price_delta_snapshot: Mapped[Decimal] = mapped_column(
        Numeric(10, 2), nullable=False
    )

    created_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), nullable=False
    )
