from __future__ import annotations

from datetime import datetime
from typing import Optional

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

from app.database import Base


class OpsAlertEvent(Base):
    """
    Persisted ops alert events.

    Used for:
    - cooldown across process restarts
    - audit/history in admin UI
    """

    __tablename__ = "ops_alert_events"

    id: Mapped[int] = mapped_column(primary_key=True, index=True)
    alert_key: Mapped[str] = mapped_column(String(80), nullable=False, index=True)
    severity: Mapped[str] = mapped_column(String(10), nullable=False, index=True)  # "warn" | "page"
    title: Mapped[str] = mapped_column(String(200), nullable=False)
    detail: Mapped[Optional[str]] = mapped_column(Text, nullable=True)

    # "sent" | "skipped" | "error"
    status: Mapped[str] = mapped_column(String(20), nullable=False, index=True)
    recipients: Mapped[Optional[str]] = mapped_column(Text, nullable=True)  # comma-separated
    send_reason: Mapped[Optional[str]] = mapped_column(String(60), nullable=True)

    created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, index=True)

    __table_args__ = (
        Index("ix_ops_alert_key_created", "alert_key", "created_at"),
        Index("ix_ops_alert_status_created", "status", "created_at"),
    )

