"""comments — the global board + unread bell (02 §3, parity).

The current table has NO row anchors; anchored comments would be a new
feature in parity clothes. Schema is future-proofed cheaply: tenant_id
NOT NULL + nullable (entity_type, entity_id) anchor columns, unused by
the R1 UI.
"""

import uuid
from datetime import datetime

from sqlalchemy import (
    CheckConstraint,
    DateTime,
    ForeignKey,
    Index,
    Text,
    Uuid,
    func,
    text,
)
from sqlalchemy.orm import Mapped, mapped_column

from app.models.base import Base


class Comment(Base):
    __tablename__ = "comments"
    __table_args__ = (
        CheckConstraint("length(trim(body)) > 0", name="ck_comments_body_nonempty"),
        # an anchor is both halves or neither
        CheckConstraint(
            "(entity_type IS NULL) = (entity_id IS NULL)",
            name="ck_comments_anchor_pair",
        ),
        Index("ix_comments_tenant_created", "tenant_id", "created_at"),
        Index(
            "ix_comments_tenant_unresolved",
            "tenant_id",
            "created_at",
            postgresql_where=text("resolved_at IS NULL"),
        ),
    )

    id: Mapped[uuid.UUID] = mapped_column(Uuid(), primary_key=True, default=uuid.uuid4)
    tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id"))
    author_id: Mapped[uuid.UUID | None] = mapped_column(
        ForeignKey("users.id", ondelete="SET NULL")
    )
    body: Mapped[str] = mapped_column(Text())
    resolved_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
    resolved_by: Mapped[uuid.UUID | None] = mapped_column(
        ForeignKey("users.id", ondelete="SET NULL")
    )
    # nullable anchor — unused by R1 UI (02 §3)
    entity_type: Mapped[str | None] = mapped_column(Text())
    entity_id: Mapped[uuid.UUID | None] = mapped_column(Uuid())
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now()
    )
