"""warehouses + locations + product_item refs

Revision ID: ad6194739559
Revises: 8b722b602a5d
Create Date: 2026-05-09 10:37:28.347627

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = 'ad6194739559'
down_revision = '8b722b602a5d'
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('warehouses',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('store_id', sa.Integer(), nullable=False),
    sa.Column('code', sa.String(length=30), nullable=False),
    sa.Column('name', sa.String(length=120), nullable=False),
    sa.Column('is_default', sa.Boolean(), nullable=False),
    sa.Column('is_active', sa.Boolean(), nullable=False),
    sa.Column('notes', sa.Text(), nullable=True),
    sa.Column('created_at', sa.DateTime(), nullable=False),
    sa.Column('updated_at', sa.DateTime(), nullable=False),
    sa.ForeignKeyConstraint(['store_id'], ['stores.id'], ),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('store_id', 'code', name='uq_warehouse_store_code')
    )
    with op.batch_alter_table('warehouses', schema=None) as batch_op:
        batch_op.create_index(batch_op.f('ix_warehouses_code'), ['code'], unique=False)
        batch_op.create_index(batch_op.f('ix_warehouses_is_active'), ['is_active'], unique=False)
        batch_op.create_index(batch_op.f('ix_warehouses_is_default'), ['is_default'], unique=False)
        batch_op.create_index(batch_op.f('ix_warehouses_store_id'), ['store_id'], unique=False)

    op.create_table('warehouse_locations',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('warehouse_id', sa.Integer(), nullable=False),
    sa.Column('code', sa.String(length=40), nullable=False),
    sa.Column('name', sa.String(length=120), nullable=True),
    sa.Column('is_active', sa.Boolean(), nullable=False),
    sa.Column('notes', sa.Text(), nullable=True),
    sa.Column('created_at', sa.DateTime(), nullable=False),
    sa.Column('updated_at', sa.DateTime(), nullable=False),
    sa.ForeignKeyConstraint(['warehouse_id'], ['warehouses.id'], ),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('warehouse_id', 'code', name='uq_location_warehouse_code')
    )
    with op.batch_alter_table('warehouse_locations', schema=None) as batch_op:
        batch_op.create_index(batch_op.f('ix_warehouse_locations_code'), ['code'], unique=False)
        batch_op.create_index(batch_op.f('ix_warehouse_locations_is_active'), ['is_active'], unique=False)
        batch_op.create_index(batch_op.f('ix_warehouse_locations_warehouse_id'), ['warehouse_id'], unique=False)

    with op.batch_alter_table('product_items', schema=None) as batch_op:
        batch_op.add_column(sa.Column('warehouse_id', sa.Integer(), nullable=True))
        batch_op.add_column(sa.Column('location_id', sa.Integer(), nullable=True))
        batch_op.create_index(batch_op.f('ix_product_items_location_id'), ['location_id'], unique=False)
        batch_op.create_index(batch_op.f('ix_product_items_warehouse_id'), ['warehouse_id'], unique=False)
        batch_op.create_foreign_key(None, 'warehouse_locations', ['location_id'], ['id'])
        batch_op.create_foreign_key(None, 'warehouses', ['warehouse_id'], ['id'])

    # === Seed: 1 almacén "PRINCIPAL" por cada sede + backfill product_items ===
    conn = op.get_bind()
    now = sa.text("CURRENT_TIMESTAMP")

    stores = conn.execute(sa.text("SELECT id FROM stores")).fetchall()
    for (store_id,) in stores:
        conn.execute(
            sa.text(
                "INSERT INTO warehouses (store_id, code, name, is_default, is_active, created_at, updated_at) "
                "VALUES (:sid, 'PRINCIPAL', 'Almacén principal', 1, 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
            ),
            {"sid": store_id},
        )

    # Backfill: cada product_item con store_id apunta al PRINCIPAL de su sede
    conn.execute(sa.text(
        "UPDATE product_items pi "
        "JOIN warehouses w ON w.store_id = pi.store_id AND w.code = 'PRINCIPAL' "
        "SET pi.warehouse_id = w.id "
        "WHERE pi.store_id IS NOT NULL AND pi.warehouse_id IS NULL"
    ))

    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('product_items', schema=None) as batch_op:
        batch_op.drop_constraint(None, type_='foreignkey')
        batch_op.drop_constraint(None, type_='foreignkey')
        batch_op.drop_index(batch_op.f('ix_product_items_warehouse_id'))
        batch_op.drop_index(batch_op.f('ix_product_items_location_id'))
        batch_op.drop_column('location_id')
        batch_op.drop_column('warehouse_id')

    with op.batch_alter_table('warehouse_locations', schema=None) as batch_op:
        batch_op.drop_index(batch_op.f('ix_warehouse_locations_warehouse_id'))
        batch_op.drop_index(batch_op.f('ix_warehouse_locations_is_active'))
        batch_op.drop_index(batch_op.f('ix_warehouse_locations_code'))

    op.drop_table('warehouse_locations')
    with op.batch_alter_table('warehouses', schema=None) as batch_op:
        batch_op.drop_index(batch_op.f('ix_warehouses_store_id'))
        batch_op.drop_index(batch_op.f('ix_warehouses_is_default'))
        batch_op.drop_index(batch_op.f('ix_warehouses_is_active'))
        batch_op.drop_index(batch_op.f('ix_warehouses_code'))

    op.drop_table('warehouses')
    # ### end Alembic commands ###
