from sqlalchemy import ForeignKey, Integer, Text
from sqlalchemy.orm import Mapped, mapped_column

from scribe.models import Base
from scribe.models.base import SoftDeleteMixin, TimestampMixin, iso


class Milestone(Base, TimestampMixin, SoftDeleteMixin):
    __tablename__ = "milestones"

    id: Mapped[int] = mapped_column(primary_key=True)
    user_id: Mapped[int] = mapped_column(Integer, ForeignKey("users.id", ondelete="CASCADE"))
    project_id: Mapped[int] = mapped_column(Integer, ForeignKey("projects.id", ondelete="CASCADE"))
    title: Mapped[str] = mapped_column(Text, default="")
    description: Mapped[str | None] = mapped_column(Text, nullable=True)
    # The plan: design/intent/purpose (markdown). The milestone is the plan
    # container; its steps live as first-class child tasks (milestone_id), not
    # as checkboxes in this body. `description` stays the one-line summary.
    body: Mapped[str | None] = mapped_column(Text, nullable=True)
    status: Mapped[str] = mapped_column(Text, default="active")
    order_index: Mapped[int] = mapped_column(Integer, default=0)

    def to_dict(self) -> dict:
        return {
            "id": self.id,
            "user_id": self.user_id,
            "project_id": self.project_id,
            "title": self.title,
            "description": self.description,
            "body": self.body,
            "status": self.status,
            "order_index": self.order_index,
            "created_at": iso(self.created_at),
            "updated_at": iso(self.updated_at),
        }
