"""sales_report

Revision ID: 8dc8e0f71a2d
Revises: 2505d6f40bee
Create Date: 2019-07-03 14:19:24.507000

"""
import logging

from alembic import op
import sqlalchemy as sa

logger = logging.getLogger(__name__)

# revision identifiers, used by Alembic.
revision = '8dc8e0f71a2d'
down_revision = '2505d6f40bee'
branch_labels = None
depends_on = None

first_agent_version = '19.7.3'


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 'sales_reports' in tables:
        logger.info("Table 'sales_reports' already exists. Skipping its migration...")
    else:
        op.create_table(
            'sales_reports',
            sa.Column('id', sa.String(length=64), primary_key=True),
            sa.Column('generated_at', sa.DateTime(), nullable=False),
            sa.Column('gross_sales_total', sa.Integer(), nullable=True),
            sa.Column('reductions_total', sa.Integer(), nullable=True),
            sa.Column('net_sales', sa.Integer(), nullable=True),
            sa.Column('taxes', sa.Integer(), nullable=True),
            sa.Column('deferred_sales_total', sa.Integer(), nullable=True),
            sa.Column('service_charges_total', sa.Integer(), nullable=True),
            sa.Column('revenue', sa.Integer(), nullable=True),
            sa.Column('payments_total', sa.Integer(), nullable=True),
            sa.Column('payouts_total', sa.Integer(), nullable=True),
        )

    if 'sales_report_payments' in tables:
        logger.info("Table 'sales_report_payments' already exists. Skipping its migration...")
    else:
        op.create_table(
            'sales_report_payments',
            sa.Column('report_id', sa.String(length=64), nullable=False),
            sa.Column('id', sa.String(length=64), nullable=False),
            sa.Column('name', sa.String(length=128), nullable=True),
            sa.Column('amount', sa.Integer(), nullable=False),
            sa.Column('quantity', sa.Integer(), nullable=False),
            sa.Column('tender_type_id', sa.String(length=64), nullable=True),
            sa.PrimaryKeyConstraint('report_id', 'id'),
            sa.ForeignKeyConstraint(
                ['report_id'],
                ['sales_reports.id'],
                name='fk_sales_report_payment_sales_report',
                onupdate='cascade',
                ondelete='cascade',
            )
        )

        with op.batch_alter_table('sales_report_payments', schema=None) as batch_op:
            batch_op.create_index('idx_sales_report_payments_report_id_id', ['report_id', 'id'], unique=True)

    if 'sales_report_payouts' in tables:
        logger.info("Table 'sales_report_payouts' already exists. Skipping its migration...")
    else:
        op.create_table(
            'sales_report_payouts',
            sa.Column('report_id', sa.String(length=64), nullable=False),
            sa.Column('id', sa.String(length=64), nullable=False),
            sa.Column('name', sa.String(length=128), nullable=True),
            sa.Column('amount', sa.Integer(), nullable=False),
            sa.Column('quantity', sa.Integer(), nullable=False),
            sa.PrimaryKeyConstraint('report_id', 'id'),
            sa.ForeignKeyConstraint(
                ['report_id'],
                ['sales_reports.id'],
                name='fk_sales_report_payout_sales_report',
                onupdate='cascade',
                ondelete='cascade',
            )
        )

        with op.batch_alter_table('sales_report_payouts', schema=None) as batch_op:
            batch_op.create_index('idx_sales_report_payouts_report_id_id', ['report_id', 'id'], unique=True)


def downgrade():
    """
    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 'sales_reports' not in tables:
        logger.info("Table 'sales_reports' does not exist. Skipping its migration...")
    else:
        op.drop_table('sales_reports')

    if 'sales_report_payments' not in tables:
        logger.info("Table 'sales_report_payments' does not exist. Skipping its migration...")
    else:
        op.drop_table('sales_report_payments')

    if 'sales_report_payouts' not in tables:
        logger.info("Table 'sales_report_payouts' does not exist. Skipping its migration...")
    else:
        op.drop_table('sales_report_payouts')
