"""Maintenance: added URL field and removed attachments.

Revision ID: aa9ed3e094d5
Revises: 3cb12dfd8d6e
Create Date: 2024-04-24 22:39:03.511051

"""

from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = "aa9ed3e094d5"
down_revision: Union[str, None] = "3cb12dfd8d6e"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None

from alembic import op
from sqlalchemy import engine_from_config
from sqlalchemy import inspect


def _table_has_column(table, column):
    config = op.get_context().config
    engine = engine_from_config(config.get_section(config.config_ini_section), prefix="sqlalchemy.")
    insp = inspect(engine)
    has_column = False
    for col in insp.get_columns(table):
        if column not in col["name"]:
            continue
        has_column = True
    return has_column


def _is_sqllite():
    return op.get_context().dialect.name == "sqlite"


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    if not _table_has_column("maintenances", "instructions_url"):
        op.add_column("maintenances", sa.Column("instructions_url", sa.String(), nullable=True))
    if _table_has_column("maintenances", "attachment"):
        if not _is_sqllite():
            op.drop_column("maintenances", "attachment")
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    if _table_has_column("maintenances", "instructions_url"):
        if not _is_sqllite():
            op.drop_column("maintenances", "instructions_url")

    if not _table_has_column("maintenances", "attachment"):
        op.add_column("maintenances", sa.Column("attachment", sa.String(), nullable=True))
    # ### end Alembic commands ###
