import enum
import uuid

from sqlalchemy import CheckConstraint, ForeignKey
from sqlalchemy import Enum as SAEnum
from sqlalchemy.orm import Mapped, mapped_column, relationship

from idlemaxx.models.base import IdlemaxBase
from idlemaxx.models.items import Item


class TradeStatus(enum.Enum):
    PENDING = "pending"
    ACCEPTED = "accepted"
    REJECTED = "rejected"


class Trade(IdlemaxBase):
    __tablename__ = "trades"
    initiator_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("characters.id"))
    counterparty_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("characters.id"))
    current_turn_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("characters.id"))
    status: Mapped[TradeStatus] = mapped_column(SAEnum(TradeStatus), default=TradeStatus.PENDING)

    offers: Mapped[list["TradeOffer"]] = relationship(
        default_factory=list,
        cascade="all, delete-orphan",
        order_by="TradeOffer.created_at",
    )


class TradeOffer(IdlemaxBase):
    __tablename__ = "trade_offers"
    trade_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("trades.id"))
    proposed_by_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("characters.id"))

    items: Mapped[list["TradeOfferItem"]] = relationship(
        default_factory=list,
        cascade="all, delete-orphan",
    )


class TradeOfferItem(IdlemaxBase):
    __tablename__ = "trade_offer_items"
    trade_offer_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("trade_offers.id"))
    offered_by_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("characters.id"))
    item: Mapped[Item] = mapped_column(SAEnum(Item))
    quantity: Mapped[int]

    __table_args__ = (CheckConstraint("quantity > 0", name="trade_offer_item_quantity_positive"),)
