BEGIN;

UPDATE fifo_stock_v2_route_rules
SET
    is_active = TRUE,
    updated_at = NOW()
WHERE flag_group_code = 'AYAM'
  AND lane = 'USABLE'
  AND function_code = 'TRANSFER_TO_LAYING_OUT'
  AND source_table = 'laying_transfer_sources';

UPDATE fifo_stock_v2_route_rules
SET
    is_active = FALSE,
    updated_at = NOW()
WHERE flag_group_code = 'AYAM'
  AND lane = 'USABLE'
  AND function_code = 'TRANSFER_TO_LAYING_OUT'
  AND source_table = 'laying_transfers';

UPDATE fifo_stock_v2_traits
SET is_active = TRUE
WHERE source_table = 'laying_transfer_sources'
  AND lane = 'USABLE';

UPDATE fifo_stock_v2_traits
SET is_active = FALSE
WHERE source_table = 'laying_transfers'
  AND lane = 'USABLE';

DROP INDEX IF EXISTS idx_laying_transfers_source_project_flock_kandang_id;
DROP INDEX IF EXISTS idx_laying_transfers_source_product_warehouse_id;

DO $$
BEGIN
    IF EXISTS (
        SELECT 1 FROM pg_constraint
        WHERE conname = 'fk_laying_transfers_source_project_flock_kandang_id'
    ) THEN
        ALTER TABLE laying_transfers
            DROP CONSTRAINT fk_laying_transfers_source_project_flock_kandang_id;
    END IF;

    IF EXISTS (
        SELECT 1 FROM pg_constraint
        WHERE conname = 'fk_laying_transfers_source_product_warehouse_id'
    ) THEN
        ALTER TABLE laying_transfers
            DROP CONSTRAINT fk_laying_transfers_source_product_warehouse_id;
    END IF;
END $$;

ALTER TABLE laying_transfers
    DROP COLUMN IF EXISTS source_project_flock_kandang_id,
    DROP COLUMN IF EXISTS source_product_warehouse_id,
    DROP COLUMN IF EXISTS source_requested_qty,
    DROP COLUMN IF EXISTS source_usage_qty,
    DROP COLUMN IF EXISTS source_pending_usage_qty;

COMMIT;
