from __future__ import annotations

from datetime import datetime

from sqlalchemy import DateTime, Integer, JSON, String, Text
from sqlalchemy.orm import Mapped, mapped_column

from app.db.session import Base


class EditorChangeEvent(Base):
    """An audit row recording an edit to a mix or an ingredient.

    Written by the editor API whenever a mix or raw material (ingredient) is
    created or changed, and read back per-entity by the History buttons on the
    Mix Editor and Ingredients Editor. `changes` holds a list of
    ``{"field", "label", "before", "after"}`` field deltas so the UI can show a
    readable before/after for each edit.
    """

    __tablename__ = "editor_change_events"

    id: Mapped[int] = mapped_column(primary_key=True)
    tenant_id: Mapped[str] = mapped_column(String(64), default="default", index=True)
    # "mix" or "ingredient" — the surface the History button lives on.
    entity_type: Mapped[str] = mapped_column(String(32), index=True)
    entity_id: Mapped[int] = mapped_column(Integer, index=True)
    action: Mapped[str] = mapped_column(String(48))
    actor_name: Mapped[str] = mapped_column(String(255), default="")
    actor_email: Mapped[str] = mapped_column(String(255), default="")
    actor_role: Mapped[str | None] = mapped_column(String(64), nullable=True)
    summary: Mapped[str] = mapped_column(Text, default="")
    changes: Mapped[list | None] = mapped_column(JSON, nullable=True)
    created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, index=True)
