-- ============================================================================
-- Fix Customer Email Index for Multi-Tenancy
-- This allows the same email to exist across different companies
-- but prevents duplicate emails within the same company
-- ============================================================================

USE PowderCoatingDb
GO

-- Step 1: Check if the old index exists
IF EXISTS (SELECT * FROM sys.indexes WHERE name = 'IX_Customers_Email' AND object_id = OBJECT_ID('Customers'))
BEGIN
    PRINT 'Dropping old IX_Customers_Email index...'

    -- Drop the old unique index that enforces global email uniqueness
    DROP INDEX IX_Customers_Email ON Customers

    PRINT 'Old index dropped successfully.'
END
ELSE
BEGIN
    PRINT 'Old index IX_Customers_Email not found (may have already been dropped).'
END
GO

-- Step 2: Create new unique index scoped to CompanyId
PRINT 'Creating new company-scoped IX_Customers_Email index...'

CREATE UNIQUE INDEX IX_Customers_Email
ON Customers (CompanyId, Email)
WHERE [Email] IS NOT NULL AND [IsDeleted] = 0
GO

PRINT 'New index created successfully!'
PRINT ''
PRINT 'The Customers table now allows:'
PRINT '  ✓ Same email across different companies'
PRINT '  ✓ Prevents duplicate emails within the same company'
PRINT '  ✓ Ignores soft-deleted records'
GO

-- Step 3: Verify the new index
SELECT
    i.name AS IndexName,
    i.is_unique AS IsUnique,
    STUFF((
        SELECT ', ' + COL_NAME(ic.object_id, ic.column_id)
        FROM sys.index_columns ic
        WHERE ic.object_id = i.object_id AND ic.index_id = i.index_id
        ORDER BY ic.key_ordinal
        FOR XML PATH('')
    ), 1, 2, '') AS IndexColumns,
    i.filter_definition AS FilterDefinition
FROM sys.indexes i
WHERE i.object_id = OBJECT_ID('Customers')
    AND i.name = 'IX_Customers_Email'
GO

PRINT ''
PRINT 'Index verification complete. You can now seed customer data!'
GO
