"""add menu item versions

Revision ID: 6ce2245413b5
Revises: 7f3a6c94e57e
Create Date: 2019-11-11 14:53:58.826269

"""
import logging

from alembic import op, context
import sqlalchemy as sa
from sqlalchemy import (
    BigInteger,
    Column,
    String,
)

logger = logging.getLogger(__name__)


# revision identifiers, used by Alembic.
revision = '6ce2245413b5'
down_revision = '7f3a6c94e57e'
branch_labels = None
depends_on = None

# TODO: Set the first_agent_version correctly before merging this revision
first_agent_version = '19.12.4'


def upgrade():
    connection = op.get_bind()
    inspector = sa.inspect(connection)
    tables = set(inspector.get_table_names())

    try:
        connection.execute("pragma foreign_keys = 0")

        if 'menu_item_versions' in tables:
            logger.info("Table 'menu_item_versions' already exists. Skipping its migration...")
        else:
            op.create_table(
                'menu_item_versions',
                Column('menu_item_id', String(64), primary_key=True),
                Column('version_string', String(64), primary_key=True),
            )

        with op.batch_alter_table('menu_item_versions', schema=None) as batch_op:
            batch_op.create_foreign_key(
                'fk_menu_item_version_menu_items',
                'menu_items',
                ['menu_item_id'],
                ['id'],
                ondelete='CASCADE',
                onupdate='CASCADE',
            )
            batch_op.create_index(
                'idx_menu_item_versions_version_string',
                ['version_string'],
                unique=False,
            )
    finally:
        connection.execute('PRAGMA foreign_keys = "1"')


def downgrade():
    current_context = context.get_context()
    inspector = sa.inspect(current_context.connection)
    tables = set(inspector.get_table_names())

    try:
        current_context.connection.execute("pragma foreign_keys = 0")

        if 'menu_item_versions' in tables:
            op.drop_table('menu_item_versions')

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