"""isolate equivalency items

Revision ID: f1a2b3c4d5e6
Revises: e4f5a6b7c8d9
Create Date: 2026-05-12 17:18:00.000000

"""
from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

revision: str = "f1a2b3c4d5e6"
down_revision: Union[str, None] = "e4f5a6b7c8d9"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # 1. Add equivalency_id column
    op.add_column(
        'equivalency_items',
        sa.Column(
            'equivalency_id',
            sa.Integer(),
            sa.ForeignKey('a76.equivalencies.id', ondelete='CASCADE'),
            nullable=True
        ),
        schema='a76'
    )
    
    # 2. Drop old unique constraint
    # Note: In some DBs we might need to specify the type, but for Postgres 'unique' or 'foreignkey' works.
    op.drop_constraint('uq_equivalency_item_fields', 'equivalency_items', schema='a76', type_='unique')
    
    # 3. Create new unique constraint including equivalency_id
    op.create_unique_constraint(
        'uq_equivalency_item_fields',
        'equivalency_items',
        ['equivalency_id', 'original_field', 'external_field', 'tenant_id', 'company_id'],
        schema='a76'
    )
    
    # 4. Increase identifier length in equivalencies table
    op.alter_column(
        'equivalencies',
        'identifier',
        type_=sa.String(50),
        existing_type=sa.String(10),
        schema='a76'
    )


def downgrade() -> None:
    # 1. Drop new unique constraint
    op.drop_constraint('uq_equivalency_item_fields', 'equivalency_items', schema='a76', type_='unique')
    
    # 2. Re-create old unique constraint
    op.create_unique_constraint(
        'uq_equivalency_item_fields',
        'equivalency_items',
        ['original_field', 'external_field', 'tenant_id', 'company_id'],
        schema='a76'
    )
    
    # 4. Revert identifier length in equivalencies table
    op.alter_column(
        'equivalencies',
        'identifier',
        type_=sa.String(10),
        existing_type=sa.String(50),
        schema='a76'
    )
    # 5. Drop equivalency_id column
    op.drop_column('equivalency_items', 'equivalency_id', schema='a76')
