from datetime import datetime
from enum import Enum
from sqlalchemy import String, Text, DateTime, ForeignKey, Integer
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.core.database import Base


class BonusAssignmentStatus(str, Enum):
    PENDING = "pending"
    COMPLETED = "completed"


class BonusAssignment(Base):
    """Бонусные челленджи для игр типа 'playthrough'"""
    __tablename__ = "bonus_assignments"

    id: Mapped[int] = mapped_column(primary_key=True)
    main_assignment_id: Mapped[int] = mapped_column(
        ForeignKey("assignments.id", ondelete="CASCADE"),
        index=True
    )
    challenge_id: Mapped[int] = mapped_column(
        ForeignKey("challenges.id", ondelete="CASCADE"),
        index=True
    )
    status: Mapped[str] = mapped_column(
        String(20),
        default=BonusAssignmentStatus.PENDING.value
    )
    proof_path: Mapped[str | None] = mapped_column(String(500), nullable=True)
    proof_url: Mapped[str | None] = mapped_column(Text, nullable=True)
    proof_comment: Mapped[str | None] = mapped_column(Text, nullable=True)
    points_earned: Mapped[int] = mapped_column(Integer, default=0)
    completed_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)

    # Relationships
    main_assignment: Mapped["Assignment"] = relationship(
        "Assignment",
        back_populates="bonus_assignments"
    )
    challenge: Mapped["Challenge"] = relationship("Challenge")
    dispute: Mapped["Dispute"] = relationship(
        "Dispute",
        back_populates="bonus_assignment",
        uselist=False,
    )
    proof_files: Mapped[list["BonusAssignmentProof"]] = relationship(
        "BonusAssignmentProof",
        back_populates="bonus_assignment",
        cascade="all, delete-orphan",
        order_by="BonusAssignmentProof.order_index"
    )
