-- V008: Add MustChangePassword column + IX_Usuario_Activo_Rol index
-- Idempotent: re-runnable without errors.
SET QUOTED_IDENTIFIER ON;
SET ANSI_NULLS ON;
SET NOCOUNT ON;
GO

-- Add MustChangePassword column (idempotent via COL_LENGTH check)
IF COL_LENGTH('dbo.Usuario', 'MustChangePassword') IS NULL
BEGIN
    ALTER TABLE dbo.Usuario
        ADD MustChangePassword BIT NOT NULL
        CONSTRAINT DF_Usuario_MustChangePassword DEFAULT(0);
    PRINT 'Column MustChangePassword added to dbo.Usuario.';
END
ELSE
    PRINT 'Column MustChangePassword already exists — skipping.';
GO

-- Compound index for listado filtrado (Activo + Rol) and anti-lockout guard
IF NOT EXISTS (
    SELECT 1 FROM sys.indexes
    WHERE name = 'IX_Usuario_Activo_Rol'
      AND object_id = OBJECT_ID('dbo.Usuario')
)
BEGIN
    CREATE INDEX IX_Usuario_Activo_Rol
        ON dbo.Usuario(Activo, Rol)
        INCLUDE (Id, Username, Email, UltimoLogin, FechaModificacion);
    PRINT 'Index IX_Usuario_Activo_Rol created.';
END
ELSE
    PRINT 'Index IX_Usuario_Activo_Rol already exists — skipping.';
GO
