import uuid

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

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


class Notification(UUIDPKMixin, TenantScopedMixin, TimestampMixin, Base):
    """A durable in-app notification — raised by a Workflow Designer step's
    notifications (on entering/leaving it, via a Connector) and by a Task's
    create_notification node. Shown in the bell of both the Studio header
    and the Public Portal header, filtered per viewer by recipient_user_id —
    see app/crud/notifications.py and app/routers/notifications.py."""

    __tablename__ = "notifications"

    title: Mapped[str] = mapped_column(String(200), nullable=False)
    message: Mapped[str] = mapped_column(String(1000), nullable=False)
    source: Mapped[str] = mapped_column(String(50), nullable=False, server_default="workflow")
    workflow_instance_id: Mapped[uuid.UUID | None] = mapped_column(
        PGUUID(as_uuid=True), ForeignKey("workflow_instances.id", ondelete="CASCADE")
    )
    connector_id: Mapped[uuid.UUID | None] = mapped_column(PGUUID(as_uuid=True), ForeignKey("connectors.id"))
    # Who this row is addressed to. NULL = the original tenant-wide broadcast
    # (every internal Studio user sees it, shared read flag) — what a
    # notification configured with no recipient roles/users still writes. A
    # targeted notification instead fans out one row per resolved user
    # (internal or Public Portal), each with its own read flag — see
    # app/crud/notifications.py::resolve_recipient_user_ids.
    recipient_user_id: Mapped[uuid.UUID | None] = mapped_column(
        PGUUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE")
    )
    read:Mapped[bool] = mapped_column(Boolean, nullable=False, server_default="false")
