"""Rename metadata to additional_data

Revision ID: 003_rename_metadata
Revises: 002_add_iot_equipment_support
Create Date: 2025-01-12 21:05:00.000000

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '003_rename_metadata'
down_revision = '002_add_iot_equipment_support'
branch_labels = None
depends_on = None


def upgrade():
    """Rename metadata columns to additional_data to avoid SQLAlchemy reserved attribute conflict"""

    # Check if columns need to be renamed (they may already be named additional_data in migration 002)
    from sqlalchemy import inspect
    from alembic import op

    connection = op.get_bind()
    inspector = inspect(connection)

    # Check equipment_connection_logs table
    if 'equipment_connection_logs' in inspector.get_table_names():
        columns = [col['name'] for col in inspector.get_columns('equipment_connection_logs')]
        if 'metadata' in columns and 'additional_data' not in columns:
            op.execute('ALTER TABLE equipment_connection_logs RENAME COLUMN metadata TO additional_data')

    # Check equipment_iot_alerts table
    if 'equipment_iot_alerts' in inspector.get_table_names():
        columns = [col['name'] for col in inspector.get_columns('equipment_iot_alerts')]
        if 'metadata' in columns and 'additional_data' not in columns:
            op.execute('ALTER TABLE equipment_iot_alerts RENAME COLUMN metadata TO additional_data')


def downgrade():
    """Revert column names back to metadata"""

    # Check if columns need to be renamed back
    from sqlalchemy import inspect
    from alembic import op

    connection = op.get_bind()
    inspector = inspect(connection)

    # Check equipment_iot_alerts table
    if 'equipment_iot_alerts' in inspector.get_table_names():
        columns = [col['name'] for col in inspector.get_columns('equipment_iot_alerts')]
        if 'additional_data' in columns and 'metadata' not in columns:
            op.execute('ALTER TABLE equipment_iot_alerts RENAME COLUMN additional_data TO metadata')

    # Check equipment_connection_logs table
    if 'equipment_connection_logs' in inspector.get_table_names():
        columns = [col['name'] for col in inspector.get_columns('equipment_connection_logs')]
        if 'additional_data' in columns and 'metadata' not in columns:
            op.execute('ALTER TABLE equipment_connection_logs RENAME COLUMN additional_data TO metadata')
