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

from app.core.database import Base


class AssignmentStatus(str, Enum):
    ACTIVE = "active"
    COMPLETED = "completed"
    DROPPED = "dropped"
    RETURNED = "returned"  # Disputed and needs to be redone


class Assignment(Base):
    __tablename__ = "assignments"

    id: Mapped[int] = mapped_column(primary_key=True)
    participant_id: Mapped[int] = mapped_column(ForeignKey("participants.id", ondelete="CASCADE"), index=True)
    challenge_id: Mapped[int] = mapped_column(ForeignKey("challenges.id", ondelete="CASCADE"))
    status: Mapped[str] = mapped_column(String(20), default=AssignmentStatus.ACTIVE.value)
    event_type: Mapped[str | None] = mapped_column(String(30), nullable=True)  # Event type when assignment was created
    is_event_assignment: Mapped[bool] = mapped_column(Boolean, default=False, index=True)  # True for Common Enemy assignments
    event_id: Mapped[int | None] = mapped_column(ForeignKey("events.id", ondelete="SET NULL"), nullable=True, index=True)  # Link to event
    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)
    streak_at_completion: Mapped[int | None] = mapped_column(Integer, nullable=True)
    started_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
    completed_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)

    # Relationships
    participant: Mapped["Participant"] = relationship("Participant", back_populates="assignments")
    challenge: Mapped["Challenge"] = relationship("Challenge", back_populates="assignments")
    event: Mapped["Event | None"] = relationship("Event", back_populates="assignments")
    dispute: Mapped["Dispute | None"] = relationship("Dispute", back_populates="assignment", uselist=False, cascade="all, delete-orphan", passive_deletes=True)
