"""SQLAlchemy model for the exposed-entity toggle table.

``ExposedEntityToggle`` stores the per-entity enable/disable state for the
MQTT / HA Discovery expose framework.  The *catalog* of what *can* be
exposed is computed dynamically by provider functions (see
``app/integrations/expose.py``); this table only records which entries the
user has explicitly enabled.

Key design decisions
--------------------
- ``key`` is a stable string identifier derived from device uuid + metric key
  (e.g. ``"modbus.<uuid>.voltage"``), so it does not drift if rows are
  deleted and re-inserted.
- Default state for an entity not yet in this table is **disabled** (false).
  ``build_catalog`` in expose.py treats a missing row as ``enabled=False``.
- Only one row per entity key (``key`` is UNIQUE).
"""

from __future__ import annotations

from datetime import datetime

from sqlalchemy import Boolean, DateTime, Integer, String
from sqlalchemy.orm import Mapped, mapped_column

from app.db import Base


class ExposedEntityToggle(Base):
    """Per-entity on/off switch for MQTT / HA Discovery publishing.

    Rows are created on demand (first toggle); entities with no row are
    treated as disabled.
    """

    __tablename__ = "exposed_entity_toggle"

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)

    # Stable entity key, e.g. "modbus.<uuid>.voltage" or "modbus.<uuid>.online".
    key: Mapped[str] = mapped_column(String(255), unique=True, nullable=False)

    # Whether this entity should be published via MQTT / HA Discovery.
    enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)

    # Last time this row was created or modified.
    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), nullable=False
    )
