"""Delete fpds_update table and move relevant dates into external_data_load_date

Revision ID: b135db94bb15
Revises: 2cd8406116b0
Create Date: 2021-10-18 11:20:57.881072

"""

# revision identifiers, used by Alembic.
revision = 'b135db94bb15'
down_revision = '2cd8406116b0'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from dataactcore.models.lookups import EXTERNAL_DATA_TYPE

def upgrade(engine_name):
    globals()["upgrade_%s" % engine_name]()


def downgrade(engine_name):
    globals()["downgrade_%s" % engine_name]()





def upgrade_data_broker():
    # ### commands auto generated by Alembic - please adjust! ###
    for e in EXTERNAL_DATA_TYPE:
        op.execute("""
            INSERT INTO external_data_type (created_at, updated_at, external_data_type_id, name, description)
            VALUES (NOW(), NOW(), {id}, '{name}', '{desc}')
            ON CONFLICT (external_data_type_id) DO UPDATE
            SET name = '{name}',
                description = '{desc}'
        """.format(id=e.id, name=e.name, desc=e.desc))
    # Insert the fpds update date if it exists. If it does, it'll be the only one with a null data type so we can set it
    op.execute("""
        INSERT INTO external_data_load_date (created_at, updated_at, external_data_type_id, last_load_date_start, last_load_date_end)
        (
            SELECT NOW(), NOW(), external_data_type_id, fpds_update.update_date, fpds_update.update_date
            FROM external_data_type AS edt, fpds_update
            WHERE NOT EXISTS (
                SELECT 1
                FROM external_data_load_date AS edld
                WHERE edld.external_data_type_id = edt.external_data_type_id
            )
                AND edt.name = 'fpds'
        )
    """)
    op.drop_table('fpds_update')

    op.execute("""
        INSERT INTO external_data_load_date (created_at, updated_at, external_data_type_id, last_load_date_start, last_load_date_end)
        (
            WITH max_office_load AS (
                SELECT MAX(updated_at) AS max_load
                FROM office)
            SELECT NOW(), NOW(), external_data_type_id, mfl.max_load, mfl.max_load
            FROM external_data_type AS edt, max_office_load AS mfl
            WHERE NOT EXISTS (
                SELECT 1
                FROM external_data_load_date AS edld
                WHERE edld.external_data_type_id = edt.external_data_type_id
            )
                AND edt.name = 'office'
        )
    """)
    pass
    # ### end Alembic commands ###


def downgrade_data_broker():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('fpds_update',
        sa.Column('created_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),
        sa.Column('updated_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),
        sa.Column('update_date', sa.DATE(), autoincrement=False, nullable=True),
        sa.Column('fpds_update_id', sa.INTEGER(), server_default=sa.text('1'), autoincrement=False, nullable=False),
        sa.PrimaryKeyConstraint('fpds_update_id', name='fpds_update_pkey')
    )
    op.execute("""
        INSERT INTO fpds_update (update_date)
        (SELECT last_load_date_start
        FROM external_data_load_date AS edld
        JOIN external_data_type AS edt
            ON edld.external_data_type_id = edt.external_data_type_id
        WHERE edt.name = 'fpds')
    """)
    op.execute("""
        DELETE FROM external_data_load_date
        USING external_data_type
        WHERE external_data_load_date.external_data_type_id = external_data_type.external_data_type_id
            AND external_data_type.name IN ('fpds', 'office')
    """)
    # ### end Alembic commands ###

