"""Operational system events (warnings/errors) for the admin UI and top-nav badge."""

from datetime import datetime

from sqlalchemy import DateTime, Index, String, Text
from sqlalchemy.orm import Mapped, mapped_column

from app.database import Base


class SystemEvent(Base):
    """Durable warning/error record (jobs, ingestion, pipelines).

    ``acknowledged_at`` is set when a user dismisses the nav badge / clears
    events — history still shows in Admin → Jobs for the retention window.
    """

    __tablename__ = "system_events"
    __table_args__ = (
        Index("ix_system_events_created_at", "created_at"),
        Index("ix_system_events_ack_created", "acknowledged_at", "created_at"),
        Index("ix_system_events_dedup_created", "dedup_key", "created_at"),
    )

    id: Mapped[int] = mapped_column(primary_key=True)
    severity: Mapped[str] = mapped_column(String(16), nullable=False)  # warning | error
    source: Mapped[str] = mapped_column(String(64), nullable=False)
    code: Mapped[str] = mapped_column(String(64), nullable=False)
    message: Mapped[str] = mapped_column(Text, nullable=False)
    symbol: Mapped[str | None] = mapped_column(String(20), nullable=True)
    dedup_key: Mapped[str | None] = mapped_column(String(200), nullable=True)
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), default=datetime.utcnow, nullable=False
    )
    acknowledged_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True
    )
