"""Add index over the draft_resources.payload["resource_id"] JSON field.

Revision ID: b5cc97666e3d
Revises: 148c032ffbd8
Create Date: 2024-06-20 17:10:13.659783

"""

import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision = "b5cc97666e3d"
down_revision = "148c032ffbd8"
branch_labels = None
depends_on = None

POSTGRES_DIALECT = "postgresql"
SQLITE_DIALECT = "sqlite"


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    dialect_name = op.get_context().dialect.name

    with op.batch_alter_table("draft_resources", schema=None) as batch_op:
        if dialect_name == POSTGRES_DIALECT:
            batch_op.create_index(
                batch_op.f("ix_draft_resources_payload_resource_id"),
                [
                    sa.text(
                        "CAST(CAST(payload ->> 'resource_id' AS VARCHAR) AS INTEGER)"
                    )
                ],
                unique=False,
            )

        elif dialect_name == SQLITE_DIALECT:
            batch_op.create_index(
                batch_op.f("ix_draft_resources_payload_resource_id"),
                [
                    sa.text(
                        "CAST(JSON_EXTRACT(payload, '$.\"resource_id\"') AS INTEGER)"
                    )
                ],
                unique=False,
            )

    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table("draft_resources", schema=None) as batch_op:
        batch_op.drop_index(batch_op.f("ix_draft_resources_payload_resource_id"))

    # ### end Alembic commands ###
