"""Adds updated_at and folder cols

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

"""

from collections.abc import Sequence

import sqlalchemy as sa
import sqlmodel
from alembic import op

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


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    conn = op.get_bind()
    inspector = sa.inspect(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)

    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)

    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    try:
        conn = op.get_bind()
        inspector = sa.inspect(conn)  # type: ignore
        column_names = [column["name"] for column in inspector.get_columns("flow")]
        with op.batch_alter_table("flow", schema=None) as batch_op:
            if "folder" in column_names:
                batch_op.drop_column("folder")
            if "updated_at" in column_names:
                batch_op.drop_column("updated_at")
    except Exception as e:
        print(e)

    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)

    # ### end Alembic commands ###
