"""Async ticket payments

Revision ID: 059619ce78d0
Revises: 643fddccc803
Create Date: 2020-02-12 21:18:33.474000

"""
from alembic import op


# revision identifiers, used by Alembic.
from sqlalchemy import PrimaryKeyConstraint, Column, String, Text, Integer, ForeignKeyConstraint

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

revision = '059619ce78d0'
down_revision = '643fddccc803'
branch_labels = None
depends_on = None

first_agent_version = '20.2.13'


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

    > with op.batch_alter_table('table_name') as batch_op:
    >     pass
    """

    connection = op.get_bind()
    try:
        connection.execute('PRAGMA foreign_keys = "0";')

        with op.batch_alter_table('ticket_close_candidates') as batch_op:
            batch_op.add_column(Column(
                'close_type',
                String(64),
                nullable=False,
                server_default="close_failure",
            ))
            batch_op.drop_index('ticket_id_idx')
            batch_op.create_index('ticket_id_idx', ['ticket_id'], unique=True)

        op.create_table(
            'async_ticket_payments',
            Column('key', SqliteSafeBigInteger(), nullable=False, autoincrement=True),
            Column('ticket_id', String(length=64), nullable=False),
            Column('type', String(length=32), nullable=False),
            Column('amount', Integer, nullable=False),
            Column('tip', Integer, nullable=False),
            Column('comment', Text, nullable=True),
            Column('full_name', String(length=128), nullable=True),
            Column('tender_type_id', String(length=64), nullable=True),
            PrimaryKeyConstraint('key'),
            ForeignKeyConstraint(
                ['ticket_id'],
                ['ticket_close_candidates.ticket_id'],
                name='fk_async_ticket_payments_ticket_close_candidates',
                onupdate='cascade',
                ondelete='cascade'
            ),
        )
    finally:
        connection.execute('PRAGMA foreign_keys = "1";')


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

    > with op.batch_alter_table('table_name') as batch_op:
    >     pass
    """

    connection = op.get_bind()
    try:
        connection.execute('PRAGMA foreign_keys = "0";')

        op.drop_table('async_ticket_payments')

        with op.batch_alter_table('ticket_close_candidates') as batch_op:
            batch_op.drop_column('close_type')
            batch_op.drop_index('ticket_id_idx')
            batch_op.create_index('ticket_id_idx', ['ticket_id'], unique=False)

    finally:
        connection.execute('PRAGMA foreign_keys = "1";')

