"""saved_filters table

Revision ID: 0029_saved_filters
Revises: 0028_user_preferences
Create Date: 2025-07-23
"""

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import UUID, JSONB

# revision identifiers
revision = "0029_saved_filters"
down_revision = "0028_user_preferences"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.create_table(
        "saved_filters",
        sa.Column("id", UUID(as_uuid=True), primary_key=True, server_default=sa.text("gen_random_uuid()")),
        sa.Column("tenant_id", UUID(as_uuid=True), nullable=False),
        sa.Column("user_id", UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False),
        sa.Column("name", sa.String(100), nullable=False),
        sa.Column("entity_type", sa.String(50), nullable=False),
        sa.Column("filter_criteria", JSONB, nullable=False, server_default=sa.text("'{}'::jsonb")),
        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()),
        sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True),
        sa.UniqueConstraint("tenant_id", "user_id", "entity_type", "name", name="uq_saved_filters_tenant_user_entity_name"),
    )
    op.create_index("ix_saved_filters_tenant_user", "saved_filters", ["tenant_id", "user_id"])
    op.create_index("ix_saved_filters_tenant_entity", "saved_filters", ["tenant_id", "entity_type"])


def downgrade() -> None:
    op.drop_index("ix_saved_filters_tenant_entity", table_name="saved_filters")
    op.drop_index("ix_saved_filters_tenant_user", table_name="saved_filters")
    op.drop_table("saved_filters")
