"""Add locationtypes + locations tree (ADR-001)

Creates the locationtypes lookup and extends locations with locationtypeid +
parentlocationid (self-FK), so sites can classify locations and build a
location tree (sections, cells, sub-cells, operations, etc.). Seeds the
canonical location types.

Revision ID: 7c03_locationtypes
Revises: 7c02_app_isrequired
Create Date: 2026-06-26

"""
from alembic import op
import sqlalchemy as sa


revision = '7c03_locationtypes'
down_revision = '7c02_app_isrequired'
branch_labels = None
depends_on = None

_TYPES = ['section', 'cell', 'subcell', 'operation', 'meetingroom', 'lab',
          'office', 'storage', 'hallway', 'networkcloset', 'building']


def upgrade():
    op.create_table(
        'locationtypes',
        sa.Column('locationtypeid', sa.Integer(), primary_key=True),
        sa.Column('locationtype', sa.String(length=50), nullable=False, unique=True),
        sa.Column('description', sa.Text(), nullable=True),
        sa.Column('createddate', sa.DateTime(), nullable=True),
        sa.Column('modifieddate', sa.DateTime(), nullable=True),
        sa.Column('isactive', sa.Boolean(), nullable=True),
    )
    with op.batch_alter_table('locations') as batch_op:
        batch_op.add_column(sa.Column('locationtypeid', sa.Integer(), nullable=True))
        batch_op.add_column(sa.Column('parentlocationid', sa.Integer(), nullable=True))
        batch_op.create_foreign_key('fk_locations_locationtype', 'locationtypes',
                                    ['locationtypeid'], ['locationtypeid'])
        batch_op.create_foreign_key('fk_locations_parent', 'locations',
                                    ['parentlocationid'], ['locationid'])

    lt = sa.table('locationtypes',
                  sa.column('locationtype', sa.String),
                  sa.column('isactive', sa.Boolean))
    op.bulk_insert(lt, [{'locationtype': t, 'isactive': True} for t in _TYPES])


def downgrade():
    with op.batch_alter_table('locations') as batch_op:
        batch_op.drop_constraint('fk_locations_parent', type_='foreignkey')
        batch_op.drop_constraint('fk_locations_locationtype', type_='foreignkey')
        batch_op.drop_column('parentlocationid')
        batch_op.drop_column('locationtypeid')
    op.drop_table('locationtypes')
