"""Simplified resource table and added JSONB

Revision ID: 6ae8af4e1863
Revises: c17df768ec71
Create Date: 2021-07-14 10:07:16.802779

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision = '6ae8af4e1863'
down_revision = 'c17df768ec71'
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('resources', sa.Column('resource_data', postgresql.JSONB(astext_type=sa.Text()), nullable=True))
    op.drop_constraint('uq_resources_external_id', 'resources', type_='unique')

    op.drop_column('resources', 'application_id')
    op.add_column('resources', sa.Column('application_id', postgresql.UUID(as_uuid=True), nullable=False))

    op.create_foreign_key(op.f('fk_resources_application_id_applications'), 'resources', 'applications', ['application_id'], ['id'], ondelete='CASCADE')
    op.drop_column('resources', 'description')
    op.drop_column('resources', 'external_id')
    op.drop_column('resources', 'name')
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('resources', sa.Column('name', sa.VARCHAR(), autoincrement=False, nullable=True))
    op.execute("UPDATE resources SET name = id")
    op.alter_column("resources", "name", nullable=False)
    op.add_column('resources', sa.Column('external_id', sa.VARCHAR(), autoincrement=False, nullable=True))
    op.add_column('resources', sa.Column('description', sa.VARCHAR(), autoincrement=False, nullable=True))
    op.drop_constraint(op.f('fk_resources_application_id_applications'), 'resources', type_='foreignkey')

    op.drop_column('resources', 'application_id')
    op.add_column('resources', sa.Column('application_id', sa.VARCHAR(), nullable=True))
    op.execute("UPDATE resources SET application_id = id")
    op.alter_column("resources", "application_id", nullable=False)

    op.create_unique_constraint('uq_resources_external_id', 'resources', ['external_id', 'application_id'])
    op.drop_column('resources', 'resource_data')
    # ### end Alembic commands ###
