"""
Migrazione 0019: Tabella permission_presets (sottoruoli/template permessi).

Aggiunge la tabella `permission_presets` che consente ad admin e supervisor
di definire template nominati di permessi riutilizzabili (es. "Operatore Archivio",
"Operatore Invio", ecc.) da applicare agli operatori sulle caselle PEC.
"""

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

revision = "0019"
down_revision = "0018"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.create_table(
        "permission_presets",
        sa.Column(
            "id",
            postgresql.UUID(as_uuid=True),
            primary_key=True,
            server_default=sa.text("gen_random_uuid()"),
            nullable=False,
        ),
        sa.Column(
            "tenant_id",
            postgresql.UUID(as_uuid=True),
            sa.ForeignKey("tenants.id", ondelete="CASCADE"),
            nullable=False,
        ),
        sa.Column("name", sa.String(100), nullable=False),
        sa.Column("description", sa.Text(), nullable=True),
        sa.Column("can_read", sa.Boolean(), nullable=False, server_default="true"),
        sa.Column("can_send", sa.Boolean(), nullable=False, server_default="false"),
        sa.Column("can_manage", sa.Boolean(), nullable=False, server_default="false"),
        sa.Column("can_conserve", sa.Boolean(), nullable=False, server_default="false"),
        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.text("now()"),
        ),
        sa.Column(
            "updated_at",
            sa.DateTime(timezone=True),
            nullable=False,
            server_default=sa.text("now()"),
        ),
    )

    # Unicita' nome per tenant
    op.create_unique_constraint(
        "uq_preset_name_tenant",
        "permission_presets",
        ["tenant_id", "name"],
    )

    # Indici
    op.create_index("idx_preset_tenant", "permission_presets", ["tenant_id"])
    op.create_index("idx_preset_created_by", "permission_presets", ["created_by"])


def downgrade() -> None:
    op.drop_index("idx_preset_created_by", table_name="permission_presets")
    op.drop_index("idx_preset_tenant", table_name="permission_presets")
    op.drop_constraint("uq_preset_name_tenant", "permission_presets", type_="unique")
    op.drop_table("permission_presets")
