from sqlalchemy import String, DateTime, Enum, Float, Integer, ForeignKey, Numeric
from sqlalchemy.orm import Mapped, mapped_column, relationship
from datetime import datetime
from decimal import Decimal
import enum
from app.database import Base


class TeamSide(enum.Enum):
    HOME = "home"
    AWAY = "away"


class SpreadBetStatus(enum.Enum):
    OPEN = "open"
    MATCHED = "matched"
    COMPLETED = "completed"
    CANCELLED = "cancelled"
    DISPUTED = "disputed"


class SpreadBet(Base):
    __tablename__ = "spread_bets"

    id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
    event_id: Mapped[int] = mapped_column(ForeignKey("sport_events.id"))
    spread: Mapped[float] = mapped_column(Float)
    team: Mapped[TeamSide] = mapped_column(Enum(TeamSide))

    creator_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
    taker_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True)

    stake_amount: Mapped[Decimal] = mapped_column(Numeric(12, 2))
    house_commission_percent: Mapped[Decimal] = mapped_column(Numeric(5, 2), default=Decimal("10.00"))

    status: Mapped[SpreadBetStatus] = mapped_column(Enum(SpreadBetStatus), default=SpreadBetStatus.OPEN)
    payout_amount: Mapped[Decimal | None] = mapped_column(Numeric(12, 2), nullable=True)
    winner_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True)

    created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
    matched_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    completed_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)

    # Relationships
    event: Mapped["SportEvent"] = relationship(back_populates="spread_bets")
    creator: Mapped["User"] = relationship(back_populates="created_spread_bets", foreign_keys=[creator_id])
    taker: Mapped["User"] = relationship(back_populates="taken_spread_bets", foreign_keys=[taker_id])
