"""send_items_candidates table

Revision ID: 7039e4722429
Revises: 83f75cbd917a
Create Date: 2019-04-11 07:53:50.918000

"""
import logging

from alembic import op
import sqlalchemy as sa

from positronics_agent.v1_0.models.mapper.sqlite_safe_big_integer import SqliteSafeBigInteger

logger = logging.getLogger(__name__)


# revision identifiers, used by Alembic.
revision = '7039e4722429'
down_revision = '83f75cbd917a'
branch_labels = None
depends_on = None

first_agent_version = '19.4.16'


def upgrade():
    """
    Use batch-operations to support sqlite

    > with op.batch_alter_table('table_name') as batch_op:
    >     pass
    """
    connection = op.get_bind()
    inspector = sa.inspect(connection)
    tables = set(inspector.get_table_names())
    if 'send_items_candidates' in tables:
        logger.info("Table 'send_items_candidates' already exists. Skipping its migration...")
    else:
        op.create_table(
            'send_items_candidates',
            sa.Column('id', SqliteSafeBigInteger(), nullable=False),
            sa.Column('store_id', sa.String(length=64), nullable=True),
            sa.Column('ticket_id', sa.String(length=64), nullable=False),
            sa.Column('created', sa.DateTime(), nullable=False),
            sa.Column('modified', sa.DateTime(), nullable=True),
            sa.Column('auth', sa.String(length=256), nullable=True),
            sa.PrimaryKeyConstraint('id')
        )
        with op.batch_alter_table('send_items_candidates', schema=None) as batch_op:
            batch_op.create_index('send_items_ticket_id_idx', ['ticket_id'], unique=False)


def downgrade():
    """
    Use batch-operations to support sqlite

    > with op.batch_alter_table('table_name') as batch_op:
    >     pass
    """
    with op.batch_alter_table('send_items_candidates', schema=None) as batch_op:
        batch_op.drop_index('send_items_ticket_id_idx')

    op.drop_table('send_items_candidates')
