"""db security constraints and token indexes

Revision ID: 20260714_0004
Revises: 20260714_0003
Create Date: 2026-07-14 13:30:00
"""

from typing import Sequence, Union

from alembic import op

revision: str = "20260714_0004"
down_revision: Union[str, None] = "20260714_0003"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    bind = op.get_bind()
    if bind.dialect.name != "sqlite":
        op.create_check_constraint(
            "ck_users_role_allowed",
            "users",
            "role IN ('user', 'admin')",
        )
        op.create_check_constraint(
            "ck_users_status_allowed",
            "users",
            "status IN ('pending', 'active', 'blocked')",
        )
        op.create_check_constraint(
            "ck_users_superuser_requires_admin",
            "users",
            "(is_superuser = false) OR (role = 'admin')",
        )
        op.create_check_constraint(
            "ck_content_pages_status_allowed",
            "content_pages",
            "status IN ('draft', 'published')",
        )
    op.create_index("idx_refresh_tokens_expires_at", "refresh_tokens", ["expires_at"], unique=False)
    op.create_index("idx_password_reset_expires_at", "password_reset_tokens", ["expires_at"], unique=False)
    op.create_index("idx_email_verify_expires_at", "email_verification_tokens", ["expires_at"], unique=False)


def downgrade() -> None:
    op.drop_index("idx_email_verify_expires_at", table_name="email_verification_tokens")
    op.drop_index("idx_password_reset_expires_at", table_name="password_reset_tokens")
    op.drop_index("idx_refresh_tokens_expires_at", table_name="refresh_tokens")
    bind = op.get_bind()
    if bind.dialect.name != "sqlite":
        op.drop_constraint("ck_content_pages_status_allowed", "content_pages", type_="check")
        op.drop_constraint("ck_users_superuser_requires_admin", "users", type_="check")
        op.drop_constraint("ck_users_status_allowed", "users", type_="check")
        op.drop_constraint("ck_users_role_allowed", "users", type_="check")
