"""events_history ORM — events 의 lifecycle 변경 이력 (append-only).

PR-1 (migrations 248~249). FK ON DELETE RESTRICT 로 부모 events row 직접 삭제 차단
(feedback_history_table_fk_restrict.md — 이력은 시점 사실).
"""

from datetime import datetime
from typing import Any

from sqlalchemy import BigInteger, DateTime, ForeignKey
from sqlalchemy.dialects.postgresql import ENUM as PgEnum
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column

from core.database import Base
from models.event import EventActorEnum

HistoryChangeKindEnum = PgEnum(
    "create",
    "reschedule",
    "defer",
    "reactivate",
    "complete",
    "cancel",
    name="history_change_kind",
    create_type=False,
)


class EventHistory(Base):
    __tablename__ = "events_history"

    id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
    event_id: Mapped[int] = mapped_column(
        BigInteger, ForeignKey("events.id", ondelete="RESTRICT"), nullable=False
    )
    changed_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), default=datetime.now, nullable=False
    )
    changed_by: Mapped[str] = mapped_column(EventActorEnum, nullable=False)
    change_kind: Mapped[str] = mapped_column(HistoryChangeKindEnum, nullable=False)
    before: Mapped[dict[str, Any] | None] = mapped_column(JSONB)
    after: Mapped[dict[str, Any]] = mapped_column(JSONB, nullable=False)
