from datetime import datetime
from typing import TYPE_CHECKING, Dict, List, Optional

from pydantic import root_validator
from sqlalchemy import Column
from sqlmodel import Field, Relationship, SQLModel

from .event_attendance import EventAttendance
from .types import TimeStamp

if TYPE_CHECKING:
    from .feedback import Feedback, FeedbackList
    from .participant import Participant, ParticipantList


class EventBase(SQLModel):
    name: str

    code: str

    valid_from: datetime = Field(
        sa_column=Column(
            TimeStamp(timezone=True),
            default=datetime.now,
            nullable=False,
        )
    )
    valid_until: datetime = Field(
        sa_column=Column(
            TimeStamp(timezone=True),
            default=datetime.now,
            nullable=False,
        )
    )

    enabled: bool = Field(default=True, nullable=False)

    @root_validator()
    def range_is_positive(cls, values: Dict[str, datetime]):
        start, end = values.get("valid_from"), values.get("valid_until")
        if start is None or end is None:
            return values
        elif end < start:
            raise ValueError("validity range cannot be negative")

        return values


class Event(EventBase, table=True):
    __tablename__ = "events"

    id: Optional[int] = 