"""add conservation fields to messages and mailbox_permissions

Revision ID: 0009
Revises: 0008
Create Date: 2026-03-27

Aggiunge:
  - messages.is_pending_conservation   BOOLEAN NOT NULL DEFAULT FALSE
  - messages.pending_conservation_at   TIMESTAMP WITH TIME ZONE
  - messages.is_conserved              BOOLEAN NOT NULL DEFAULT FALSE
  - messages.conserved_at              TIMESTAMP WITH TIME ZONE
  - mailbox_permissions.can_conserve   BOOLEAN NOT NULL DEFAULT FALSE
"""

from alembic import op
import sqlalchemy as sa

# revision identifiers
revision = "0009"
down_revision = "0008"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # Nuovi campi sulla tabella messages
    op.add_column(
        "messages",
        sa.Column(
            "is_pending_conservation",
            sa.Boolean(),
            nullable=False,
            server_default=sa.text("false"),
        ),
    )
    op.add_column(
        "messages",
        sa.Column(
            "pending_conservation_at",
            sa.DateTime(timezone=True),
            nullable=True,
        ),
    )
    op.add_column(
        "messages",
        sa.Column(
            "is_conserved",
            sa.Boolean(),
            nullable=False,
            server_default=sa.text("false"),
        ),
    )
    op.add_column(
        "messages",
        sa.Column(
            "conserved_at",
            sa.DateTime(timezone=True),
            nullable=True,
        ),
    )

    # Indici parziali per query sulle cartelle Conservazione
    op.create_index(
        "idx_messages_pending_conservation",
        "messages",
        ["tenant_id"],
        postgresql_where=sa.text("is_pending_conservation = true"),
    )
    op.create_index(
        "idx_messages_conserved",
        "messages",
        ["tenant_id"],
        postgresql_where=sa.text("is_conserved = true"),
    )

    # Permesso can_conserve sulla tabella mailbox_permissions
    op.add_column(
        "mailbox_permissions",
        sa.Column(
            "can_conserve",
            sa.Boolean(),
            nullable=False,
            server_default=sa.text("false"),
        ),
    )


def downgrade() -> None:
    op.drop_column("mailbox_permissions", "can_conserve")
    op.drop_index("idx_messages_conserved", table_name="messages")
    op.drop_index("idx_messages_pending_conservation", table_name="messages")
    op.drop_column("messages", "conserved_at")
    op.drop_column("messages", "is_conserved")
    op.drop_column("messages", "pending_conservation_at")
    op.drop_column("messages", "is_pending_conservation")
