"""Add alerts and alert_settings tables

Revision ID: e5f7a9b1cd34
Revises: 8ccb553ff975
Create Date: 2026-05-20 10:00:00.000000

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = 'e5f7a9b1cd34'
down_revision: Union[str, Sequence[str], None] = '8ccb553ff975'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    """Create alerts and alert_settings tables."""
    # 创建 alerts 表
    op.create_table(
        'alerts',
        sa.Column('id', sa.Uuid(as_uuid=True), primary_key=True),
        sa.Column('brand_id', sa.Uuid(as_uuid=True),
                  sa.ForeignKey('brands.id', ondelete='CASCADE'), nullable=False),
        sa.Column('user_id', sa.Uuid(as_uuid=True), nullable=False),
        sa.Column('alert_type', sa.String(50), nullable=False,
                  comment='告警类型: score_drop / score_rise / negative_sentiment / competitor_overtake / new_platform_mention'),
        sa.Column('severity', sa.String(20), nullable=False,
                  comment='严重程度: critical / warning / info'),
        sa.Column('title', sa.String(200), nullable=False),
        sa.Column('message', sa.Text(), nullable=False),
        sa.Column('data', sa.JSON(), nullable=True,
                  comment='告警相关数据（JSON）'),
        sa.Column('is_read', sa.Boolean(), default=False, nullable=False),
        sa.Column('created_at', sa.DateTime(), server_default=sa.func.now(), nullable=False),
    )

    # 创建 alerts 表的索引
    op.create_index('idx_alerts_user_id', 'alerts', ['user_id'])
    op.create_index('idx_alerts_brand_id', 'alerts', ['brand_id'])
    op.create_index('idx_alerts_alert_type', 'alerts', ['alert_type'])
    op.create_index('idx_alerts_is_read', 'alerts', ['is_read'])
    op.create_index('idx_alerts_created_at', 'alerts', ['created_at'])
    op.create_index('idx_alerts_user_read', 'alerts', ['user_id', 'is_read'])

    # 创建 alert_settings 表
    op.create_table(
        'alert_settings',
        sa.Column('id', sa.Uuid(as_uuid=True), primary_key=True),
        sa.Column('brand_id', sa.Uuid(as_uuid=True),
                  sa.ForeignKey('brands.id', ondelete='CASCADE'), nullable=False),
        sa.Column('user_id', sa.Uuid(as_uuid=True), nullable=False),
        sa.Column('alert_type', sa.String(50), nullable=False,
                  comment='告警类型: score_drop / score_rise / negative_sentiment / competitor_overtake / new_platform_mention'),
        sa.Column('enabled', sa.Boolean(), default=True, nullable=False),
        sa.Column('threshold', sa.Float(), nullable=True,
                  comment='阈值（如评分下降超过5分触发）'),
        sa.Column('created_at', sa.DateTime(), server_default=sa.func.now(), nullable=False),
        sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now(), onupdate=sa.func.now(), nullable=False),
    )

    # 创建 alert_settings 表的索引
    op.create_index('idx_alert_settings_brand_id', 'alert_settings', ['brand_id'])
    op.create_index('idx_alert_settings_user_id', 'alert_settings', ['user_id'])
    op.create_index('idx_alert_settings_brand_type', 'alert_settings', ['brand_id', 'alert_type'], unique=True)


def downgrade() -> None:
    """Drop alerts and alert_settings tables."""
    op.drop_index('idx_alert_settings_brand_type', table_name='alert_settings')
    op.drop_index('idx_alert_settings_user_id', table_name='alert_settings')
    op.drop_index('idx_alert_settings_brand_id', table_name='alert_settings')
    op.drop_table('alert_settings')

    op.drop_index('idx_alerts_user_read', table_name='alerts')
    op.drop_index('idx_alerts_created_at', table_name='alerts')
    op.drop_index('idx_alerts_is_read', table_name='alerts')
    op.drop_index('idx_alerts_alert_type', table_name='alerts')
    op.drop_index('idx_alerts_brand_id', table_name='alerts')
    op.drop_index('idx_alerts_user_id', table_name='alerts')
    op.drop_table('alerts')
