-- =============================================
-- Delete All Customers for Testing
-- WARNING: This will delete ALL customer data!
-- =============================================

USE PowderCoatingDb;
GO

BEGIN TRANSACTION;

BEGIN TRY
    PRINT 'Starting customer deletion...';

    -- Count customers before deletion
    DECLARE @CustomerCount INT;
    SELECT @CustomerCount = COUNT(*) FROM Customers;
    PRINT 'Found ' + CAST(@CustomerCount AS VARCHAR) + ' customers to delete';

    -- Option 1: Delete related data first (safest)
    -- Update Jobs to remove customer references
    PRINT 'Removing customer references from Jobs...';
    UPDATE Jobs SET CustomerId = NULL WHERE CustomerId IS NOT NULL;

    -- Update Quotes to remove customer references
    PRINT 'Removing customer references from Quotes...';
    UPDATE Quotes SET CustomerId = NULL WHERE CustomerId IS NOT NULL;

    -- Delete all customers (hard delete)
    PRINT 'Deleting all customers...';
    DELETE FROM Customers;

    -- Verify deletion
    SELECT @CustomerCount = COUNT(*) FROM Customers;
    PRINT 'Remaining customers: ' + CAST(@CustomerCount AS VARCHAR);

    PRINT 'Customer deletion completed successfully!';
    COMMIT TRANSACTION;
    PRINT 'Transaction committed.';

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

GO

-- Verify the results
SELECT
    'Customers' AS TableName,
    COUNT(*) AS RecordCount
FROM Customers
UNION ALL
SELECT
    'Jobs with NULL CustomerId',
    COUNT(*)
FROM Jobs
WHERE CustomerId IS NULL
UNION ALL
SELECT
    'Quotes with NULL CustomerId',
    COUNT(*)
FROM Quotes
WHERE CustomerId IS NULL;
GO
