"""create_payment_processors_and_merchants

Revision ID: db875614d5cf
Revises: 2f2346b8b7cb
Create Date: 2020-03-09 19:07:58.883000

"""
import logging

from alembic import op
import sqlalchemy as sa

logger = logging.getLogger(__name__)


# revision identifiers, used by Alembic.
revision = 'db875614d5cf'
down_revision = '2f2346b8b7cb'
branch_labels = None
depends_on = None

first_agent_version = '20.3.9'


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

    if 'payment_processors' in tables:
        logger.info("Table 'payment_processors' already exists. Skipping its migration...")
    else:
        op.create_table(
            'payment_processors',
            sa.Column('name', sa.String(length=128), nullable=True),
            sa.Column('id', sa.String(length=64), nullable=False),
            sa.PrimaryKeyConstraint('id'),
        )

    if 'merchants' in tables:
        logger.info("Table 'merchants' already exists. Skipping its migration...")
    else:
        op.create_table(
            'merchants',
            sa.Column('name', sa.String(length=128), nullable=True),
            sa.Column('merchant_id', sa.String(length=64), nullable=True),
            sa.Column('payment_processor_id', sa.String(length=64), nullable=False),
            sa.Column('id', sa.String(length=64), nullable=False),
            sa.ForeignKeyConstraint(
                ['payment_processor_id'],
                ['payment_processors.id'],
                name='fk_merchants_payment_processor',
                onupdate='cascade',
                ondelete='cascade',
            ),
            sa.PrimaryKeyConstraint('id'),
        )


def downgrade():
    op.drop_table('merchants')
    op.drop_table('payment_processors')
