SELECT
    [Id],
    [RunId],
    [TenantId],
    [WorkspaceId],
    [WorkspaceName],
    [MemberId],
    [MemberEmail],
    [MemberRole],
    [Plan],
    [Status],
    [Rule],
    [DeactivatedAt]
FROM [dbo].[DelinquentMemberEnforcementEvents]
WHERE (@TenantId IS NULL
   OR [TenantId] = @TenantId)
  AND (@From IS NULL
   OR [DeactivatedAt] >= @From)
  AND (@To IS NULL
   OR [DeactivatedAt] <= @To)
  AND (@Plan IS NULL
   OR [Plan] = @Plan)
  AND (@Status IS NULL
   OR [Status] = @Status)
  AND (@Rule IS NULL
   OR [Rule] = @Rule)
  AND (@WorkspaceQuery IS NULL
   OR [WorkspaceName] LIKE '%' + @WorkspaceQuery + '%'
   OR CONVERT(NVARCHAR(36), [WorkspaceId]) LIKE '%' + @WorkspaceQuery + '%')
  AND (@MemberQuery IS NULL
   OR [MemberEmail] LIKE '%' + @MemberQuery + '%'
   OR CONVERT(NVARCHAR(36), [MemberId]) LIKE '%' + @MemberQuery + '%')
ORDER BY [DeactivatedAt] DESC
OFFSET @Offset ROWS FETCH NEXT @PageSize ROWS ONLY;

SELECT COUNT(1)
FROM [dbo].[DelinquentMemberEnforcementEvents]
WHERE (@TenantId IS NULL
   OR [TenantId] = @TenantId)
  AND (@From IS NULL
   OR [DeactivatedAt] >= @From)
  AND (@To IS NULL
   OR [DeactivatedAt] <= @To)
  AND (@Plan IS NULL
   OR [Plan] = @Plan)
  AND (@Status IS NULL
   OR [Status] = @Status)
  AND (@Rule IS NULL
   OR [Rule] = @Rule)
  AND (@WorkspaceQuery IS NULL
   OR [WorkspaceName] LIKE '%' + @WorkspaceQuery + '%'
   OR CONVERT(NVARCHAR(36), [WorkspaceId]) LIKE '%' + @WorkspaceQuery + '%')
  AND (@MemberQuery IS NULL
   OR [MemberEmail] LIKE '%' + @MemberQuery + '%'
   OR CONVERT(NVARCHAR(36), [MemberId]) LIKE '%' + @MemberQuery + '%');
