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

from app.core.database import Base


class SwapRequestStatus(str, Enum):
    PENDING = "pending"
    ACCEPTED = "accepted"
    DECLINED = "declined"
    CANCELLED = "cancelled"  # Cancelled by requester or event ended


class SwapRequest(Base):
    __tablename__ = "swap_requests"

    id: Mapped[int] = mapped_column(primary_key=True)
    event_id: Mapped[int] = mapped_column(
        ForeignKey("events.id", ondelete="CASCADE"),
        index=True
    )
    from_participant_id: Mapped[int] = mapped_column(
        ForeignKey("participants.id", ondelete="CASCADE"),
        index=True
    )
    to_participant_id: Mapped[int] = mapped_column(
        ForeignKey("participants.id", ondelete="CASCADE"),
        index=True
    )
    from_assignment_id: Mapped[int] = mapped_column(
        ForeignKey("assignments.id", ondelete="CASCADE")
    )
    to_assignment_id: Mapped[int] = mapped_column(
        ForeignKey("assignments.id", ondelete="CASCADE")
    )
    status: Mapped[str] = mapped_column(
        String(20),
        default=SwapRequestStatus.PENDING.value
    )
    created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
    responded_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)

    # Relationships
    event: Mapped["Event"] = relationship("Event")
    from_participant: Mapped["Participant"] = relationship(
        "Participant",
        foreign_keys=[from_participant_id]
    )
    to_participant: Mapped["Participant"] = relationship(
        "Participant",
        foreign_keys=[to_participant_id]
    )
    from_assignment: Mapped["Assignment"] = relationship(
        "Assignment",
        foreign_keys=[from_assignment_id]
    )
    to_assignment: Mapped["Assignment"] = relationship(
        "Assignment",
        foreign_keys=[to_assignment_id]
    )
