"""Custom field searchable flag (customfields.searchable)

Adds a boolean customfields.searchable column (default false). When true, the
field's stored values are matched by global search and a hit routes to the
owning asset's detail page.

Idempotent guard so it is safe on a partially-migrated box; real downgrade.

Revision ID: 7d24_customfield_searchable
Revises: 7d23_user_mustchangepassword
Create Date: 2026-07-12

"""
from alembic import op
import sqlalchemy as sa


revision = '7d24_customfield_searchable'
down_revision = '7d23_user_mustchangepassword'
branch_labels = None
depends_on = None


def upgrade():
    bind = op.get_bind()
    insp = sa.inspect(bind)

    if 'customfields' not in insp.get_table_names():
        return
    columns = {c['name'] for c in insp.get_columns('customfields')}
    if 'searchable' in columns:
        return

    op.add_column(
        'customfields',
        sa.Column('searchable', sa.Boolean(),
                  nullable=False, server_default=sa.false()))


def downgrade():
    bind = op.get_bind()
    insp = sa.inspect(bind)

    if 'customfields' not in insp.get_table_names():
        return
    columns = {c['name'] for c in insp.get_columns('customfields')}
    if 'searchable' not in columns:
        return

    op.drop_column('customfields', 'searchable')
