/*
    Pre-Deployment Script — dashboard/saw quick wins batch.

    Per-release: holds only the pre-deployment steps for the feature shipping in
    this release. Previous releases' steps are already in main and are not repeated.
*/

PRINT '=== Pre-Deployment: START ===';

-- Reclassification no longer targets work orders. Backfill NewProductId from the
-- old WO's product before dropping the dead column, so existing reclassified
-- bundles keep showing their new product. sp_executesql defers binding the
-- possibly-absent NewWorkOrderId column.
IF COL_LENGTH('FAB.BundleReclassifications', 'NewWorkOrderId') IS NOT NULL
BEGIN
    EXEC sp_executesql N'
        UPDATE r
        SET r.[NewProductId] = wo.[ProductId]
        FROM [FAB].[BundleReclassifications] r
        INNER JOIN [FAB].[WorkOrders] wo ON wo.[WorkOrderId] = r.[NewWorkOrderId]
        WHERE r.[NewProductId] IS NULL';

    IF OBJECT_ID('FAB.FK_BundleReclassifications_NewWO', 'F') IS NOT NULL
        ALTER TABLE FAB.BundleReclassifications DROP CONSTRAINT FK_BundleReclassifications_NewWO;
    ALTER TABLE FAB.BundleReclassifications DROP COLUMN NewWorkOrderId;
    PRINT 'Backfilled NewProductId and dropped FAB.BundleReclassifications.NewWorkOrderId';
END

PRINT '=== Pre-Deployment: COMPLETE ===';
