"""MpsCartOffer — association between a cart and the accepted offer
whose agreed amount drives its total.

A cart with a cart_offer row pays at the offer's current_amount_in_cents,
not the product's listed price. The route that creates this association
(/o/{id}/checkout — commit 8) verifies the offer is in ACCEPTED state
and the user is the buyer.

Many-to-one to Cart, one-to-one to MpsOffer.
"""

import uuid

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

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


class MpsCartOffer(RBase, Base):
    id = Column(UUIDType, primary_key=True, index=True)
    cart_id = Column(UUIDType, foreign_key("Cart", "id"), nullable=False)
    offer_id = Column(
        UUIDType, foreign_key("MpsOffer", "id"), nullable=False, index=True,
    )
    created_timestamp = Column(BigInteger, nullable=False)

    cart = relationship(
        argument="Cart",
        backref=backref("cart_offers", cascade="all, delete-orphan"),
    )
    offer = relationship(argument="MpsOffer")

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