import uuid

from sqlalchemy import ForeignKey, String
from sqlalchemy.dialects.postgresql import JSONB, UUID as PGUUID
from sqlalchemy.orm import Mapped, mapped_column

from app.models.base import Base, TenantScopedMixin, TimestampMixin, UUIDPKMixin


class Component(UUIDPKMixin, TenantScopedMixin, TimestampMixin, Base):
    """A tenant-scoped, reusable Page-block-or-Form-field snippet — saved
    once from Page Designer/Form Designer's canvas, then inserted as an
    independent copy elsewhere (never live-linked back to this row; see
    routers/components.py's own docstring for why).

    `definition` is always a JSON array so both kinds share one column
    shape: for kind="page_block" it holds exactly one PageBlockDef (the
    selected block plus its full children/groups subtree, see
    app/schemas/navigation.py::PageBlockDef); for kind="form_field" it
    holds one or more FormFieldDef entries in canvas order (see
    app/schemas/workflow.py::FormFieldDef).
    """

    __tablename__ = "components"

    kind: Mapped[str] = mapped_column(String(20), nullable=False)
    name: Mapped[str] = mapped_column(String(150), nullable=False)
    description: Mapped[str | None] = mapped_column(String(500))
    definition: Mapped[list] = mapped_column(JSONB, nullable=False)
    created_by: Mapped[uuid.UUID | None] = mapped_column(PGUUID(as_uuid=True), ForeignKey("users.id"))
