"""Request ID decimal column

Revision ID: 040f2dfde5a5
Revises: b4257b10daaf
Create Date: 2023-08-10 08:58:22.052336

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

# revision identifiers, used by Alembic.
revision = '040f2dfde5a5'
down_revision = 'b4257b10daaf'
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('call_requests', sa.Column('request_id', sa.DECIMAL(), nullable=True))
    op.create_index(op.f('ix_call_requests_request_id'), 'call_requests', ['request_id'], unique=False)
    op.create_unique_constraint(op.f('uq_call_requests_registered_contract_id'), 'call_requests', ['registered_contract_id', 'request_id'])

    # Manual
    # Fetch IDs of duplicates for 'dropper-v0.2.0' call_request_type and delete it
    op.execute("""WITH Duplicates AS (
    SELECT 
        id,
        registered_contract_id,
        call_request_type_name,
        parameters->'requestID' AS request_id,
        created_at,
        ROW_NUMBER() OVER (
            PARTITION BY 
                registered_contract_id,
                call_request_type_name,
                parameters->'requestID' 
            ORDER BY created_at ASC
        ) AS row_num
    FROM call_requests
    WHERE call_request_type_name = 'dropper-v0.2.0' 
),
DeleteDuplicates AS (
SELECT id
FROM 
    Duplicates
WHERE
    row_num < (
        SELECT COUNT(*) FROM Duplicates d2
        WHERE d2.registered_contract_id = Duplicates.registered_contract_id
        AND d2.call_request_type_name = Duplicates.call_request_type_name
        AND d2.request_id = Duplicates.request_id
    )
)
DELETE FROM call_requests WHERE id IN (SELECT id FROM DeleteDuplicates);""")
               
    # Fulfill not empty requestID values
    op.execute("UPDATE call_requests SET request_id = CAST(parameters->>'requestID' AS DECIMAL) WHERE parameters->>'requestID' IS NOT NULL;")
    # Fulfill raw types with random requestID
    op.execute("UPDATE call_requests SET request_id = FLOOR(RANDOM()* 120500600 + 120400600) WHERE parameters->>'requestID' IS NULL;")
    op.alter_column("call_requests", "request_id", nullable=False)

    # Other
    op.create_unique_constraint(op.f('uq_blockchains_id'), 'blockchains', ['id'])
    op.create_unique_constraint(op.f('uq_call_request_types_name'), 'call_request_types', ['name'])
    op.create_unique_constraint(op.f('uq_metatx_requesters_id'), 'metatx_requesters', ['id'])
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index(op.f('ix_call_requests_request_id'), table_name='call_requests')
    op.drop_column('call_requests', 'request_id')
    # ### end Alembic commands ###
