"""MpsCartAuction — association between a cart and the auction whose
winning bid drives its total.

A cart with a cart_auction row pays at the auction's winning_bid amount,
not the product's listed price. The route that creates this association
(/a/{id}/checkout — commit 8) verifies the user is the winner.

The relationship is many-to-one to Cart and one-to-one to MpsAuction
(an auction has at most one cart in the wild — once paid, state flips
to SETTLED and the association sticks for audit but no other cart is
created against the same auction).
"""

import uuid

from sqlalchemy import Column, BigInteger
from sqlalchemy.orm import relationship, backref

from .meta import Base, RBase, UUIDType, foreign_key, now_timestamp


class MpsCartAuction(RBase, Base):
    id = Column(UUIDType, primary_key=True, index=True)
    cart_id = Column(UUIDType, foreign_key("Cart", "id"), nullable=False)
    auction_id = Column(
        UUIDType, foreign_key("MpsAuction", "id"), nullable=False, index=True,
    )
    created_timestamp = Column(BigInteger, nullable=False)

    cart = relationship(
        argument="Cart",
        backref=backref("cart_auctions", cascade="all, delete-orphan"),
    )
    auction = relationship(argument="MpsAuction")

    def __init__(self, cart=None, auction=None):
        self.id = uuid.uuid1()
        self.cart = cart
        self.auction = auction
        self.created_timestamp = now_timestamp()
