"""Adds updated_at and folder cols

Revision ID: 7d2162acc8b2
Revises: f5ee9749d1a6
Create Date: 2023-11-21 20:56:53.998781

"""

from typing import Sequence, Union

import sqlalchemy as sa
import sqlmodel
from alembic import op
from sqlalchemy.engine.reflection import Inspector

# revision identifiers, used by Alembic.
revision: str = "7d2162acc8b2"
down_revision: Union[str, None] = "f5ee9749d1a6"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    conn = op.get_bind()
    inspector = Inspector.from_engine(conn)  # type: ignore
    api_key_columns = [column["name"] for column in inspector.get_columns("apikey")]
    flow_columns = [column["name"] for column in inspector.get_columns("flow")]

    try:
        if "name" in api_key_columns:
            with op.batch_alter_table("apikey", schema=None) as batch_op:
                batch_op.alter_column(
                    "name", existing_type=sa.VARCHAR(), nullable=False
                )
    except Exception as e:
        print(e)

        pass
    try:
        with op.batch_alter_table("flow", schema=None) as batch_op:
            if "updated_at" not in flow_columns:
                batch_op.add_column(
                    sa.Column("updated_at", sa.DateTime(), nullable=True)
                )
            if "folder" not in flow_columns:
                batch_op.add_column(
                    sa.Column(
                        "folder", sqlmodel.sql.sqltypes.AutoString(), nullable=True
                    )
                )
    except Exception as e:
        print(e)

        pass

    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    try:
        with op.batch_alter_table("flow", schema=None) as batch_op:
            batch_op.drop_column("folder")
            batch_op.drop_column("updated_at")
    except Exception as e:
        print(e)
        pass

    try:

        with op.batch_alter_table("apikey", schema=None) as batch_op:
            batch_op.alter_column("name", existing_type=sa.VARCHAR(), nullable=True)
    except Exception as e:
        print(e)
        pass

    # ### end Alembic commands ###
