-- =============================================
-- Fix Catalog Items with Empty Names
-- Sets Name = SKU for items with NULL or empty names
-- =============================================

USE PowderCoatingDb;
GO

BEGIN TRANSACTION;

BEGIN TRY
    PRINT 'Fixing catalog items with empty names...';

    -- Count items with empty names
    DECLARE @EmptyNameCount INT;
    SELECT @EmptyNameCount = COUNT(*)
    FROM CatalogItems
    WHERE Name IS NULL OR LTRIM(RTRIM(Name)) = '';

    PRINT 'Found ' + CAST(@EmptyNameCount AS VARCHAR) + ' items with empty names';

    -- Update items: set Name = SKU where Name is empty
    UPDATE CatalogItems
    SET Name = SKU,
        UpdatedAt = GETUTCDATE()
    WHERE Name IS NULL OR LTRIM(RTRIM(Name)) = '';

    -- Verify the fix
    SELECT @EmptyNameCount = COUNT(*)
    FROM CatalogItems
    WHERE Name IS NULL OR LTRIM(RTRIM(Name)) = '';

    PRINT 'Remaining items with empty names: ' + CAST(@EmptyNameCount AS VARCHAR);

    PRINT 'Catalog item names fixed successfully!';
    COMMIT TRANSACTION;
    PRINT 'Transaction committed.';

END TRY
BEGIN CATCH
    PRINT 'Error occurred: ' + ERROR_MESSAGE();
    ROLLBACK TRANSACTION;
    PRINT 'Transaction rolled back.';
END CATCH;

GO

-- Show sample of fixed items
SELECT TOP 10
    Id,
    SKU,
    Name,
    Description,
    DefaultPrice,
    IsActive
FROM CatalogItems
ORDER BY UpdatedAt DESC;

GO
