import uuid
from datetime import datetime

from sqlalchemy import String, Boolean, Float, ForeignKey, Index, func
from sqlalchemy import Uuid
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.database import Base


class AlertSetting(Base):
    """告警设置表 - 每个品牌每种告警类型一条记录"""
    __tablename__ = "alert_settings"

    id: Mapped[uuid.UUID] = mapped_column(
        Uuid(as_uuid=True),
        primary_key=True,
        default=uuid.uuid4,
    )
    brand_id: Mapped[uuid.UUID] = mapped_column(
        Uuid(as_uuid=True),
        ForeignKey("brands.id", ondelete="CASCADE"),
        nullable=False,
    )
    user_id: Mapped[uuid.UUID] = mapped_column(
        Uuid(as_uuid=True),
        nullable=False,
        index=True,
    )
    alert_type: Mapped[str] = mapped_column(
        String(50), nullable=False,
        comment="告警类型: score_drop / score_rise / negative_sentiment / competitor_overtake / new_platform_mention",
    )
    enabled: Mapped[bool] = mapped_column(
        Boolean, default=True, nullable=False,
    )
    threshold: Mapped[float | None] = mapped_column(
        Float, nullable=True,
        comment="阈值（如评分下降超过5分触发）",
    )
    created_at: Mapped[datetime] = mapped_column(
        server_default=func.now(),
        nullable=False,
    )
    updated_at: Mapped[datetime] = mapped_column(
        server_default=func.now(),
        onupdate=func.now(),
        nullable=False,
    )

    brand: Mapped["Brand"] = relationship("Brand")  # noqa: F821

    __table_args__ = (
        Index("idx_alert_settings_brand_id", "brand_id"),
        Index("idx_alert_settings_user_id", "user_id"),
        Index("idx_alert_settings_brand_type", "brand_id", "alert_type", unique=True),
    )
