BEGIN;

ALTER TABLE stock_allocations
    ADD COLUMN IF NOT EXISTS allocation_purpose VARCHAR(32);

UPDATE stock_allocations
SET allocation_purpose = 'CONSUME'
WHERE allocation_purpose IS NULL
   OR BTRIM(allocation_purpose) = '';

ALTER TABLE stock_allocations
    ALTER COLUMN allocation_purpose SET DEFAULT 'CONSUME',
    ALTER COLUMN allocation_purpose SET NOT NULL;

ALTER TABLE stock_allocations
    DROP CONSTRAINT IF EXISTS stock_allocations_allocation_purpose_check;

ALTER TABLE stock_allocations
    ADD CONSTRAINT stock_allocations_allocation_purpose_check
    CHECK (allocation_purpose IN ('CONSUME', 'TRACE_CHICKIN'));

CREATE INDEX IF NOT EXISTS idx_stock_allocations_purpose_status
    ON stock_allocations (allocation_purpose, status);

CREATE INDEX IF NOT EXISTS idx_stock_allocations_purpose_usable_active
    ON stock_allocations (allocation_purpose, usable_type, usable_id)
    WHERE status = 'ACTIVE';

CREATE INDEX IF NOT EXISTS idx_stock_allocations_purpose_stockable_active
    ON stock_allocations (allocation_purpose, stockable_type, stockable_id)
    WHERE status = 'ACTIVE';

COMMIT;
