"""v3.11: Added token container template table and a 'template' column in the token container table.

Revision ID: c128c01a5520
Revises: 69e7817b9863
Create Date: 2024-09-12 09:33:18.656723

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.exc import OperationalError, ProgrammingError

# revision identifiers, used by Alembic.
revision = 'c128c01a5520'
down_revision = '7301d5130c3a'


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    try:
        op.create_table('tokencontainertemplate',
                        sa.Column('id', sa.Integer(), sa.Identity(always=False), nullable=False),
                        sa.Column('options', sa.Unicode(length=2000), nullable=True),
                        sa.Column('name', sa.Unicode(length=200), nullable=True),
                        sa.Column('container_type', sa.Unicode(length=100), nullable=False),
                        sa.Column('default', sa.Boolean(), nullable=False),
                        sa.PrimaryKeyConstraint('id'),
                        mysql_row_format='DYNAMIC'
                        )
    except (OperationalError, ProgrammingError) as exx:
        if "already exists" in str(exx.orig).lower():
            print("Table 'tokencontainertemplate' already exists.")
        else:
            print("Could not add table 'tokencontainertemplate' to database.")
            print(exx)

    migration_context = op.get_context()
    try:
        if migration_context.dialect.name in ['sqlite']:
            with op.batch_alter_table("tokencontainer") as batch_op:
                batch_op.add_column(sa.Column("template_id", sa.Integer(),
                                              sa.ForeignKey('tokencontainertemplate.id',
                                                            name="tokencontainertemplate_id")))
        else:
            op.add_column('tokencontainer',
                          sa.Column("template_id", sa.Integer(),
                                    sa.ForeignKey('tokencontainertemplate.id',
                                                  name="tokencontainertemplate_id")))
    except (OperationalError, ProgrammingError) as exx:
        if "already exists" in str(exx.orig).lower() or "duplicate column name" in str(exx.orig).lower():
            print("Foreign key 'template_id' already exist.")
        else:
            print("Could not add foreign key 'template_id' to table 'tokencontainer'.")
            print(exx)
    # ### end Alembic commands ###


def downgrade():
    migration_context = op.get_context()
    # ### commands auto generated by Alembic - please adjust! ###
    try:
        if migration_context.dialect.name in ['sqlite']:
            with op.batch_alter_table("tokencontainer") as batch_op:
                batch_op.drop_constraint("tokencontainertemplate_id", type_="foreignkey")
        else:
            op.drop_constraint('tokencontainertemplate_id', 'tokencontainer', 'foreignkey')
    except (OperationalError, ProgrammingError) as exx:
        msg = str(exx.orig).lower()
        if "no such column" in msg or "does not exist" in msg or "no such constraint" in msg:
            print("Foreign key 'template_id' already removed.")
        else:
            print("Could not remove foreign key 'template_id' from table 'tokencontainer'.")
            print(exx)
    except (KeyError, ValueError) as exx:
        msg = str(exx).lower()
        if "no such column" in msg or "does not exist" in msg or "no such constraint" in msg:
            print("Foreign key 'template_id' already removed.")
        else:
            print("Could not remove foreign key 'template_id' from table 'tokencontainer'.")
            print(exx)

    try:
        op.drop_column('tokencontainer', 'template_id')
    except (OperationalError, ProgrammingError) as exx:
        msg = str(exx.orig).lower()
        if "no such column" in msg or "does not exist" in msg:
            print("Column 'template_id' already removed.")
        else:
            print("Could not remove column 'template_id' from table 'tokencontainer'.")
            print(exx)

    try:
        op.drop_table('tokencontainertemplate')
    except (OperationalError, ProgrammingError) as exx:
        msg = str(exx.orig).lower()
        if "no such table" in msg or "unknown table" in msg or "does not exist" in msg:
            print("Table 'tokencontainertemplate' already removed.")
        else:
            print("Could not remove table 'tokencontainertemplate'.")
            print(exx)
    # ### end Alembic commands ###
