"""
Migrazione 0011: tabelle routing_rules, routing_rule_conditions, routing_rule_actions
(Feature 2 – Regole di smistamento automatico).
"""

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

revision = "0011"
down_revision = "0010"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # Tabella principale regole
    op.create_table(
        "routing_rules",
        sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
        sa.Column(
            "tenant_id",
            postgresql.UUID(as_uuid=True),
            sa.ForeignKey("tenants.id", ondelete="CASCADE"),
            nullable=False,
        ),
        sa.Column("name", sa.String(255), nullable=False),
        sa.Column("description", sa.Text, nullable=True),
        sa.Column("is_active", sa.Boolean, nullable=False, server_default="true"),
        sa.Column("priority", sa.Integer, nullable=False, server_default="100"),
        sa.Column("stop_processing", sa.Boolean, nullable=False, server_default="true"),
        sa.Column(
            "created_by",
            postgresql.UUID(as_uuid=True),
            sa.ForeignKey("users.id", ondelete="SET NULL"),
            nullable=True,
        ),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            nullable=False,
            server_default=sa.func.now(),
        ),
        sa.Column(
            "updated_at",
            sa.DateTime(timezone=True),
            nullable=False,
            server_default=sa.func.now(),
        ),
    )
    op.create_index("idx_routing_rules_tenant", "routing_rules", ["tenant_id"])
    op.create_index(
        "idx_routing_rules_active",
        "routing_rules",
        ["tenant_id", "priority"],
        postgresql_where=sa.text("is_active = true"),
    )

    # Condizioni delle regole
    op.create_table(
        "routing_rule_conditions",
        sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
        sa.Column(
            "rule_id",
            postgresql.UUID(as_uuid=True),
            sa.ForeignKey("routing_rules.id", ondelete="CASCADE"),
            nullable=False,
        ),
        # field: from_address | to_address | subject | mailbox_id | pec_type
        sa.Column("field", sa.String(50), nullable=False),
        # operator: contains | equals | starts_with | ends_with | regex | not_contains
        sa.Column("operator", sa.String(30), nullable=False, server_default="contains"),
        sa.Column("value", sa.Text, nullable=False),
    )
    op.create_index(
        "idx_routing_conditions_rule",
        "routing_rule_conditions",
        ["rule_id"],
    )

    # Azioni delle regole
    op.create_table(
        "routing_rule_actions",
        sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
        sa.Column(
            "rule_id",
            postgresql.UUID(as_uuid=True),
            sa.ForeignKey("routing_rules.id", ondelete="CASCADE"),
            nullable=False,
        ),
        # action_type: apply_label | assign_vbox | mark_read | mark_starred | notify_webhook
        sa.Column("action_type", sa.String(50), nullable=False),
        # action_value: UUID di label/vbox, URL del webhook, ecc.
        sa.Column("action_value", sa.Text, nullable=True),
    )
    op.create_index(
        "idx_routing_actions_rule",
        "routing_rule_actions",
        ["rule_id"],
    )


def downgrade() -> None:
    op.drop_index("idx_routing_actions_rule", table_name="routing_rule_actions")
    op.drop_table("routing_rule_actions")
    op.drop_index("idx_routing_conditions_rule", table_name="routing_rule_conditions")
    op.drop_table("routing_rule_conditions")
    op.drop_index("idx_routing_rules_active", table_name="routing_rules")
    op.drop_index("idx_routing_rules_tenant", table_name="routing_rules")
    op.drop_table("routing_rules")
