from sqlalchemy import (
    Column,
    Integer,
    DateTime,
    Enum,
    UniqueConstraint,
    Index,
    ForeignKey,
    func,
)
from sqlalchemy.dialects.mysql import BIGINT
from app.core.time import now
from app.db.base import Base

class CompetitionParticipant(Base):
    __tablename__ = "competition_participants"
    __table_args__ = (
        UniqueConstraint("competition_id", "user_id", name="uk_competition_user"),
        Index("idx_total_steps", "competition_id", "total_steps"),
    )

    id = Column(BIGINT(unsigned=True), primary_key=True, autoincrement=True)
    competition_id = Column(BIGINT(unsigned=True), ForeignKey("competitions.id", ondelete="CASCADE"), nullable=False)
    user_id = Column(BIGINT(unsigned=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
    total_steps = Column(Integer, nullable=False, default=0)
    rank = Column(Integer, nullable=True)
    points_earned = Column(Integer, nullable=False, default=0)
    status = Column(
        Enum("active", "withdrawn", name="competition_participant_status"),
        nullable=False,
        default="active",
    )
    joined_at = Column(DateTime, nullable=False, default=now)
    updated_at = Column(
        DateTime, nullable=False, default=now, onupdate=now
    )