-- DBAOps Enterprise™ - Create Tables
-- Generated: 2026-02-05 08:20:54
-- Tables: 544
USE [DBAOpsRepository];
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'admin' AND TABLE_NAME = 'ErrorLog')
BEGIN
    CREATE TABLE [admin].[ErrorLog] (
    [ErrorID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [ErrorMessage] nvarchar(MAX) NULL,
    [ErrorDate] datetime2 NULL DEFAULT (sysdatetime()),
    [ErrorSource] varchar(100) NULL,
    [ProcessID] int NULL
    );
    PRINT 'Created [admin].[ErrorLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ai' AND TABLE_NAME = 'AnomalyDetection')
BEGIN
    CREATE TABLE [ai].[AnomalyDetection] (
    [AnomalyID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [MetricName] nvarchar(200) NOT NULL,
    [MetricValue] decimal(18,4) NOT NULL,
    [ExpectedValue] decimal(18,4) NULL,
    [DeviationPercent] decimal(10,2) NULL,
    [AnomalyScore] decimal(5,2) NULL,
    [AnomalyType] nvarchar(100) NULL,
    [DetectedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [ai].[AnomalyDetection]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ai' AND TABLE_NAME = 'AnomalyDetections')
BEGIN
    CREATE TABLE [ai].[AnomalyDetections] (
    [AnomalyID] bigint NOT NULL IDENTITY(1,1),
    [DetectedDate] datetime2 NULL DEFAULT (sysdatetime()),
    [ServerName] nvarchar(256) NULL,
    [MetricName] nvarchar(200) NULL,
    [ExpectedValue] decimal(18,4) NULL,
    [ActualValue] decimal(18,4) NULL,
    [DeviationPercent] decimal(10,2) NULL,
    [AnomalyScore] decimal(5,2) NULL,
    [AIAnalysis] nvarchar(MAX) NULL,
    [RecommendedAction] nvarchar(MAX) NULL,
    [IsAcknowledged] bit NULL DEFAULT ((0))
    );
    PRINT 'Created [ai].[AnomalyDetections]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ai' AND TABLE_NAME = 'APIUsageLog')
BEGIN
    CREATE TABLE [ai].[APIUsageLog] (
    [LogID] int NOT NULL IDENTITY(1,1),
    [RequestDate] datetime2 NULL DEFAULT (getdate()),
    [CallingProcedure] nvarchar(256) NULL,
    [PromptTokens] int NULL,
    [CompletionTokens] int NULL,
    [TotalTokens] int NULL,
    [EstimatedCostUSD] decimal(10,6) NULL,
    [ResponseTimeMS] int NULL,
    [StatusCode] int NULL,
    [ErrorMessage] nvarchar(MAX) NULL,
    [ServerContext] nvarchar(512) NULL,
    [RequestType] nvarchar(100) NULL
    );
    PRINT 'Created [ai].[APIUsageLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ai' AND TABLE_NAME = 'Configuration')
BEGIN
    CREATE TABLE [ai].[Configuration] (
    [ConfigID] int NOT NULL IDENTITY(1,1),
    [ConfigKey] nvarchar(200) NOT NULL,
    [ConfigValue] nvarchar(MAX) NULL,
    [Description] nvarchar(1000) NULL,
    [IsEncrypted] bit NULL DEFAULT ((0)),
    [ModifiedDate] datetime2 NULL DEFAULT (sysdatetime()),
    [ModifiedBy] nvarchar(256) NULL DEFAULT (suser_name())
    );
    PRINT 'Created [ai].[Configuration]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ai' AND TABLE_NAME = 'DiagnosticLog')
BEGIN
    CREATE TABLE [ai].[DiagnosticLog] (
    [LogID] bigint NOT NULL IDENTITY(1,1),
    [RequestTime] datetime2 NULL DEFAULT (sysdatetime()),
    [RequestType] nvarchar(100) NULL,
    [ServerName] nvarchar(256) NULL,
    [Category] nvarchar(100) NULL,
    [InputContext] nvarchar(MAX) NULL,
    [Prompt] nvarchar(MAX) NULL,
    [Response] nvarchar(MAX) NULL,
    [TokensUsed] int NULL,
    [ResponseTimeMs] int NULL,
    [Status] nvarchar(40) NULL,
    [ErrorMessage] nvarchar(MAX) NULL,
    [RequestedBy] nvarchar(256) NULL DEFAULT (suser_name())
    );
    PRINT 'Created [ai].[DiagnosticLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ai' AND TABLE_NAME = 'fact_Diagnostics')
BEGIN
    CREATE TABLE [ai].[fact_Diagnostics] (
    [DiagnosticID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DiagnosticType] nvarchar(100) NOT NULL,
    [IssueSummary] nvarchar(1000) NOT NULL,
    [AIAnalysis] nvarchar(MAX) NULL,
    [RemediationSteps] nvarchar(MAX) NULL,
    [Severity] int NOT NULL DEFAULT ((2)),
    [DetectedDate] datetime2 NOT NULL DEFAULT (getdate()),
    [ResolvedDate] datetime2 NULL,
    [ResolvedBy] nvarchar(200) NULL,
    [ResolutionNotes] nvarchar(MAX) NULL,
    [Status] nvarchar(40) NOT NULL DEFAULT ('Open'),
    [AutoResolved] bit NOT NULL DEFAULT ((0)),
    [HelpfulRating] int NULL,
    [RelatedAlertID] bigint NULL,
    [AIConfidence] decimal(5,2) NULL
    );
    PRINT 'Created [ai].[fact_Diagnostics]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ai' AND TABLE_NAME = 'MLPredictions')
BEGIN
    CREATE TABLE [ai].[MLPredictions] (
    [PredictionID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [PredictionType] nvarchar(200) NOT NULL,
    [ResourceName] nvarchar(512) NULL,
    [CurrentValue] decimal(18,4) NULL,
    [PredictedValue] decimal(18,4) NULL,
    [PredictedDate] date NULL,
    [ConfidencePercent] decimal(5,2) NULL,
    [RiskLevel] nvarchar(40) NULL,
    [Recommendation] nvarchar(1000) NULL,
    [PredictedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [ai].[MLPredictions]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ai' AND TABLE_NAME = 'Recommendations')
BEGIN
    CREATE TABLE [ai].[Recommendations] (
    [RecommendationID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [RecommendationType] nvarchar(200) NOT NULL,
    [Title] nvarchar(400) NOT NULL,
    [Description] nvarchar(MAX) NULL,
    [Impact] nvarchar(40) NULL,
    [Effort] nvarchar(40) NULL,
    [ActionScript] nvarchar(MAX) NULL,
    [GeneratedAt] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [Status] nvarchar(100) NOT NULL DEFAULT ('New'),
    [ImplementedAt] datetime2 NULL
    );
    PRINT 'Created [ai].[Recommendations]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ai' AND TABLE_NAME = 'SearchHistory')
BEGIN
    CREATE TABLE [ai].[SearchHistory] (
    [SearchID] bigint NOT NULL IDENTITY(1,1),
    [SearchTime] datetime2 NULL DEFAULT (sysdatetime()),
    [NaturalLanguageQuery] nvarchar(MAX) NULL,
    [GeneratedSQL] nvarchar(MAX) NULL,
    [ResultCount] int NULL,
    [ExecutionTimeMs] int NULL,
    [SearchedBy] nvarchar(256) NULL DEFAULT (suser_name())
    );
    PRINT 'Created [ai].[SearchHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'alert' AND TABLE_NAME = 'ActiveAlert')
BEGIN
    CREATE TABLE [alert].[ActiveAlert] (
    [ActiveAlertID] bigint NOT NULL IDENTITY(1,1),
    [AlertDefID] int NOT NULL,
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NULL,
    [AlertTitle] nvarchar(1000) NOT NULL,
    [AlertMessage] nvarchar(MAX) NULL,
    [Severity] nvarchar(40) NOT NULL,
    [CurrentValue] decimal(18,4) NULL,
    [ThresholdValue] decimal(18,4) NULL,
    [FirstOccurrence] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [LastOccurrence] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [OccurrenceCount] int NOT NULL DEFAULT ((1)),
    [Status] nvarchar(100) NOT NULL DEFAULT ('Active'),
    [AcknowledgedBy] nvarchar(256) NULL,
    [AcknowledgedAt] datetime2 NULL,
    [CorrelationID] uniqueidentifier NULL
    );
    PRINT 'Created [alert].[ActiveAlert]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'alert' AND TABLE_NAME = 'AlertCorrelation')
BEGIN
    CREATE TABLE [alert].[AlertCorrelation] (
    [CorrelationID] uniqueidentifier NOT NULL DEFAULT (newid()),
    [RootCauseAlertID] bigint NULL,
    [CorrelationPattern] nvarchar(400) NULL,
    [AlertCount] int NOT NULL DEFAULT ((0)),
    [FirstAlertTime] datetime2 NOT NULL,
    [LastAlertTime] datetime2 NOT NULL,
    [Status] nvarchar(100) NOT NULL DEFAULT ('Active')
    );
    PRINT 'Created [alert].[AlertCorrelation]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'alert' AND TABLE_NAME = 'AlertDefinition')
BEGIN
    CREATE TABLE [alert].[AlertDefinition] (
    [AlertDefID] int NOT NULL IDENTITY(1,1),
    [AlertName] nvarchar(400) NOT NULL,
    [AlertCategory] nvarchar(200) NOT NULL,
    [Description] nvarchar(1000) NULL,
    [Severity] nvarchar(40) NOT NULL,
    [IsEnabled] bit NOT NULL DEFAULT ((1)),
    [ThresholdType] nvarchar(100) NULL,
    [ThresholdValue] decimal(18,4) NULL,
    [ThresholdOperator] nvarchar(20) NULL,
    [DurationMinutes] int NULL,
    [CooldownMinutes] int NULL DEFAULT ((60)),
    [NotifyEmail] bit NOT NULL DEFAULT ((1)),
    [NotifyTeams] bit NOT NULL DEFAULT ((0)),
    [RunbookURL] nvarchar(1000) NULL,
    [CreatedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [alert].[AlertDefinition]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'alert' AND TABLE_NAME = 'AlertEscalation')
BEGIN
    CREATE TABLE [alert].[AlertEscalation] (
    [EscalationID] int NOT NULL IDENTITY(1,1),
    [AlertDefID] int NULL,
    [Severity] nvarchar(40) NULL,
    [EscalationLevel] int NOT NULL,
    [EscalateAfterMinutes] int NOT NULL,
    [NotifyEmail] nvarchar(1000) NULL,
    [NotifyTeamsWebhook] nvarchar(1000) NULL,
    [IsEnabled] bit NOT NULL DEFAULT ((1))
    );
    PRINT 'Created [alert].[AlertEscalation]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'alert' AND TABLE_NAME = 'AlertHistory')
BEGIN
    CREATE TABLE [alert].[AlertHistory] (
    [AlertHistoryID] bigint NOT NULL IDENTITY(1,1),
    [AlertDefID] int NOT NULL,
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NULL,
    [AlertTitle] nvarchar(1000) NOT NULL,
    [AlertMessage] nvarchar(MAX) NULL,
    [Severity] nvarchar(40) NOT NULL,
    [CurrentValue] decimal(18,4) NULL,
    [FirstOccurrence] datetime2 NOT NULL,
    [LastOccurrence] datetime2 NOT NULL,
    [OccurrenceCount] int NOT NULL,
    [DurationMinutes] int NULL,
    [Status] nvarchar(100) NOT NULL,
    [ResolvedAt] datetime2 NULL,
    [ResolvedBy] nvarchar(256) NULL,
    [AutoResolved] bit NOT NULL DEFAULT ((0)),
    [ArchivedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [alert].[AlertHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'alert' AND TABLE_NAME = 'AlertNotificationLog')
BEGIN
    CREATE TABLE [alert].[AlertNotificationLog] (
    [NotificationID] bigint NOT NULL IDENTITY(1,1),
    [ActiveAlertID] bigint NULL,
    [NotificationType] nvarchar(100) NOT NULL,
    [Recipient] nvarchar(1000) NULL,
    [Subject] nvarchar(1000) NULL,
    [Status] nvarchar(100) NOT NULL,
    [ErrorMessage] nvarchar(MAX) NULL,
    [SentAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [alert].[AlertNotificationLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'alert' AND TABLE_NAME = 'AlertStatistics')
BEGIN
    CREATE TABLE [alert].[AlertStatistics] (
    [StatID] int NOT NULL IDENTITY(1,1),
    [AlertDefID] int NOT NULL,
    [StatDate] date NOT NULL,
    [ServerName] nvarchar(256) NULL,
    [TotalOccurrences] int NOT NULL DEFAULT ((0)),
    [AutoResolvedCount] int NOT NULL DEFAULT ((0)),
    [FalsePositiveCount] int NOT NULL DEFAULT ((0))
    );
    PRINT 'Created [alert].[AlertStatistics]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'alert' AND TABLE_NAME = 'AlertSuppression')
BEGIN
    CREATE TABLE [alert].[AlertSuppression] (
    [SuppressionID] int NOT NULL IDENTITY(1,1),
    [AlertDefID] int NULL,
    [ServerName] nvarchar(256) NULL,
    [SuppressionType] nvarchar(100) NOT NULL,
    [StartTime] datetime2 NOT NULL,
    [EndTime] datetime2 NOT NULL,
    [Reason] nvarchar(1000) NULL,
    [CreatedBy] nvarchar(256) NULL,
    [IsActive] bit NOT NULL DEFAULT ((1))
    );
    PRINT 'Created [alert].[AlertSuppression]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'alert' AND TABLE_NAME = 'AlertThreshold')
BEGIN
    CREATE TABLE [alert].[AlertThreshold] (
    [ThresholdID] int NOT NULL IDENTITY(1,1),
    [AlertDefID] int NOT NULL,
    [ServerName] nvarchar(256) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [ThresholdValue] decimal(18,4) NOT NULL,
    [IsEnabled] bit NOT NULL DEFAULT ((1))
    );
    PRINT 'Created [alert].[AlertThreshold]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'alert' AND TABLE_NAME = 'CriticalServerAlertLog')
BEGIN
    CREATE TABLE [alert].[CriticalServerAlertLog] (
    [AlertID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [AlertType] nvarchar(100) NOT NULL,
    [CurrentValue] decimal(10,2) NULL,
    [ThresholdValue] decimal(10,2) NULL,
    [AlertSentAt] datetime NOT NULL DEFAULT (getdate()),
    [Recommendation] nvarchar(1000) NULL,
    [RemediationAttempted] bit NULL DEFAULT ((0)),
    [RemediationResult] nvarchar(1000) NULL
    );
    PRINT 'Created [alert].[CriticalServerAlertLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'alert' AND TABLE_NAME = 'DiskSpaceAlertConfig')
BEGIN
    CREATE TABLE [alert].[DiskSpaceAlertConfig] (
    [ConfigID] int NOT NULL IDENTITY(1,1),
    [AlertLevel] nvarchar(40) NOT NULL,
    [FreePercentThreshold] decimal(5,2) NOT NULL,
    [AlertIntervalMinutes] int NOT NULL,
    [AlertColor] nvarchar(20) NOT NULL,
    [EmailEnabled] bit NULL DEFAULT ((1)),
    [IsActive] bit NULL DEFAULT ((1))
    );
    PRINT 'Created [alert].[DiskSpaceAlertConfig]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'alert' AND TABLE_NAME = 'DiskSpaceAlertLog')
BEGIN
    CREATE TABLE [alert].[DiskSpaceAlertLog] (
    [AlertID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DriveLetter] char(3) NOT NULL,
    [FreePercent] decimal(5,2) NULL,
    [AlertLevel] nvarchar(40) NULL,
    [AlertColor] nvarchar(40) NULL,
    [AlertTime] datetime2 NULL DEFAULT (sysdatetime()),
    [EmailSent] bit NULL DEFAULT ((0)),
    [EmailSentTime] datetime2 NULL,
    [AlertSentAt] datetime NULL,
    [UsedPercent] decimal(5,2) NULL,
    [Severity] nvarchar(40) NULL
    );
    PRINT 'Created [alert].[DiskSpaceAlertLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'alert' AND TABLE_NAME = 'VeeamBackupAlerts')
BEGIN
    CREATE TABLE [alert].[VeeamBackupAlerts] (
    [AlertID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [JobName] nvarchar(512) NULL,
    [BackupType] nvarchar(100) NULL,
    [Status] nvarchar(100) NULL,
    [ErrorMessage] nvarchar(MAX) NULL,
    [DatabasesProtected] int NULL,
    [DatabasesExcluded] int NULL,
    [DatabasesError] int NULL,
    [DetectedAt] datetime2 NULL DEFAULT (sysdatetime()),
    [AlertSent] bit NULL DEFAULT ((0)),
    [AlertSentAt] datetime2 NULL,
    [ResolvedAt] datetime2 NULL
    );
    PRINT 'Created [alert].[VeeamBackupAlerts]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Alerting' AND TABLE_NAME = 'AlertRules')
BEGIN
    CREATE TABLE [Alerting].[AlertRules] (
    [RuleID] int NOT NULL IDENTITY(1,1),
    [RuleName] nvarchar(200) NOT NULL,
    [Category] varchar(50) NOT NULL,
    [Severity] varchar(20) NOT NULL,
    [IsEnabled] bit NOT NULL DEFAULT ((1)),
    [CheckIntervalMinutes] int NOT NULL DEFAULT ((15)),
    [LastCheckTime] datetime2 NULL,
    [ThresholdValue] int NULL,
    [ThresholdUnit] varchar(20) NULL,
    [EmailRecipients] nvarchar(2000) NULL,
    [SendToTeams] bit NOT NULL DEFAULT ((0)),
    [Description] nvarchar(1000) NULL,
    [CreatedDate] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [ModifiedDate] datetime2 NULL
    );
    PRINT 'Created [Alerting].[AlertRules]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Alerting' AND TABLE_NAME = 'AlertSuppressionRules')
BEGIN
    CREATE TABLE [Alerting].[AlertSuppressionRules] (
    [SuppressionID] int NOT NULL IDENTITY(1,1),
    [RuleID] int NULL,
    [ServerName] nvarchar(256) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [SuppressionMinutes] int NOT NULL DEFAULT ((60)),
    [StartTime] time NULL,
    [EndTime] time NULL,
    [DaysOfWeek] varchar(20) NULL,
    [Reason] nvarchar(1000) NULL,
    [IsEnabled] bit NOT NULL DEFAULT ((1)),
    [CreatedDate] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [ExpirationDate] datetime2 NULL
    );
    PRINT 'Created [Alerting].[AlertSuppressionRules]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'alerts' AND TABLE_NAME = 'AlertSubscription')
BEGIN
    CREATE TABLE [alerts].[AlertSubscription] (
    [SubscriptionId] int NOT NULL IDENTITY(1,1),
    [SubscriberName] nvarchar(256) NOT NULL,
    [SubscriberPhone] varchar(20) NULL,
    [SubscriberEmail] nvarchar(512) NULL,
    [AlertCategory] varchar(50) NOT NULL,
    [MinimumSeverity] varchar(20) NOT NULL DEFAULT ('Warning'),
    [ServerFilter] nvarchar(512) NULL,
    [DatabaseFilter] nvarchar(512) NULL,
    [Channels] varchar(100) NOT NULL DEFAULT ('Email'),
    [QuietHoursStart] time NULL,
    [QuietHoursEnd] time NULL,
    [IsActive] bit NOT NULL DEFAULT ((1)),
    [CreatedAt] datetime2 NOT NULL DEFAULT (getdate()),
    [ModifiedAt] datetime2 NULL
    );
    PRINT 'Created [alerts].[AlertSubscription]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'alerts' AND TABLE_NAME = 'AlertThrottleHistory')
BEGIN
    CREATE TABLE [alerts].[AlertThrottleHistory] (
    [ThrottleId] int NOT NULL IDENTITY(1,1),
    [AlertKey] varchar(500) NOT NULL,
    [FirstOccurrence] datetime2 NOT NULL,
    [LastOccurrence] datetime2 NOT NULL,
    [OccurrenceCount] int NOT NULL DEFAULT ((1)),
    [ThrottledCount] int NOT NULL DEFAULT ((0))
    );
    PRINT 'Created [alerts].[AlertThrottleHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'alerts' AND TABLE_NAME = 'NotificationLog')
BEGIN
    CREATE TABLE [alerts].[NotificationLog] (
    [NotificationId] int NOT NULL IDENTITY(1,1),
    [AlertId] varchar(50) NOT NULL,
    [Channel] varchar(20) NOT NULL,
    [Recipient] nvarchar(512) NOT NULL,
    [Message] nvarchar(MAX) NOT NULL,
    [Priority] varchar(20) NOT NULL,
    [Status] varchar(20) NOT NULL,
    [Provider] varchar(50) NULL,
    [ProviderMessageId] varchar(100) NULL,
    [ErrorMessage] nvarchar(MAX) NULL,
    [SentAt] datetime2 NOT NULL DEFAULT (getdate()),
    [DeliveredAt] datetime2 NULL
    );
    PRINT 'Created [alerts].[NotificationLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'alerts' AND TABLE_NAME = 'RecentAlerts')
BEGIN
    CREATE TABLE [alerts].[RecentAlerts] (
    [AlertID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [AlertTime] datetime NOT NULL,
    [Severity] nvarchar(40) NOT NULL,
    [AlertType] nvarchar(100) NULL,
    [AlertSource] nvarchar(200) NULL,
    [AlertMessage] nvarchar(MAX) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [ObjectName] nvarchar(512) NULL,
    [MetricValue] decimal(18,2) NULL,
    [ThresholdValue] decimal(18,2) NULL,
    [IsResolved] bit NULL DEFAULT ((0)),
    [ResolvedDate] datetime NULL,
    [ResolvedBy] nvarchar(256) NULL,
    [AcknowledgedDate] datetime NULL,
    [AcknowledgedBy] nvarchar(256) NULL,
    [Notes] nvarchar(MAX) NULL,
    [CollectedDate] datetime2 NULL DEFAULT (getdate()),
    [CollectedAt] datetime NOT NULL DEFAULT (getdate())
    );
    PRINT 'Created [alerts].[RecentAlerts]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'analytics' AND TABLE_NAME = 'AnomalyBaselines')
BEGIN
    CREATE TABLE [analytics].[AnomalyBaselines] (
    [BaselineId] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [MetricName] nvarchar(200) NOT NULL,
    [AvgValue] decimal(18,4) NULL,
    [MinValue] decimal(18,4) NULL,
    [MaxValue] decimal(18,4) NULL,
    [StdDeviation] decimal(18,4) NULL,
    [SampleCount] int NULL,
    [LastUpdated] datetime2 NULL DEFAULT (getdate())
    );
    PRINT 'Created [analytics].[AnomalyBaselines]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'analytics' AND TABLE_NAME = 'CapacityForecasts')
BEGIN
    CREATE TABLE [analytics].[CapacityForecasts] (
    [ForecastId] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [ResourceType] nvarchar(100) NOT NULL,
    [ResourceName] nvarchar(512) NULL,
    [CurrentSizeGB] decimal(18,2) NULL,
    [CurrentUsedPercent] decimal(5,2) NULL,
    [DailyGrowthGB] decimal(18,4) NULL,
    [DaysUntilFull] int NULL,
    [PredictedFullDate] date NULL,
    [Severity] nvarchar(40) NULL,
    [Recommendation] nvarchar(1000) NULL,
    [ConfidencePercent] decimal(5,2) NULL,
    [ForecastedAt] datetime2 NULL DEFAULT (getdate())
    );
    PRINT 'Created [analytics].[CapacityForecasts]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'analytics' AND TABLE_NAME = 'DetectedAnomalies')
BEGIN
    CREATE TABLE [analytics].[DetectedAnomalies] (
    [AnomalyId] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [MetricName] nvarchar(200) NOT NULL,
    [DetectedAt] datetime2 NULL DEFAULT (getdate()),
    [ActualValue] decimal(18,4) NULL,
    [ExpectedValue] decimal(18,4) NULL,
    [DeviationPercent] decimal(10,2) NULL,
    [Severity] nvarchar(40) NULL,
    [IsAcknowledged] bit NULL DEFAULT ((0)),
    [AcknowledgedBy] nvarchar(256) NULL,
    [Notes] nvarchar(1000) NULL
    );
    PRINT 'Created [analytics].[DetectedAnomalies]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'analytics' AND TABLE_NAME = 'fact_AIInteractions')
BEGIN
    CREATE TABLE [analytics].[fact_AIInteractions] (
    [InteractionID] bigint NOT NULL IDENTITY(1,1),
    [UserName] nvarchar(200) NOT NULL,
    [InteractionType] nvarchar(100) NOT NULL,
    [UserQuery] nvarchar(MAX) NOT NULL,
    [AIResponse] nvarchar(MAX) NULL,
    [ServerContext] nvarchar(256) NULL,
    [Tokens] int NULL,
    [ResponseTimeMS] int NULL,
    [InteractionTime] datetime2 NOT NULL DEFAULT (getdate()),
    [UserRating] int NULL,
    [WasHelpful] bit NULL,
    [FollowUpAction] nvarchar(200) NULL,
    [SessionID] nvarchar(200) NULL
    );
    PRINT 'Created [analytics].[fact_AIInteractions]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'analytics' AND TABLE_NAME = 'fact_SearchActivity')
BEGIN
    CREATE TABLE [analytics].[fact_SearchActivity] (
    [SearchID] bigint NOT NULL IDENTITY(1,1),
    [UserName] nvarchar(200) NOT NULL,
    [SearchQuery] nvarchar(1000) NOT NULL,
    [SearchScope] nvarchar(100) NOT NULL,
    [SearchFilters] nvarchar(MAX) NULL,
    [ResultsFound] int NOT NULL,
    [TopResultClicked] nvarchar(1000) NULL,
    [ClickedResultRank] int NULL,
    [SearchTime] datetime2 NOT NULL DEFAULT (getdate()),
    [ResponseTimeMS] int NULL,
    [Helpful] bit NULL,
    [SessionID] nvarchar(200) NULL
    );
    PRINT 'Created [analytics].[fact_SearchActivity]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'analytics' AND TABLE_NAME = 'FailurePredictions')
BEGIN
    CREATE TABLE [analytics].[FailurePredictions] (
    [PredictionId] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [PredictionType] nvarchar(100) NOT NULL,
    [ObjectName] nvarchar(512) NULL,
    [PredictedFailureDate] date NULL,
    [Probability] decimal(5,2) NULL,
    [RiskLevel] nvarchar(40) NULL,
    [Reason] nvarchar(1000) NULL,
    [RecommendedAction] nvarchar(1000) NULL,
    [PredictedAt] datetime2 NULL DEFAULT (getdate()),
    [IsResolved] bit NULL DEFAULT ((0))
    );
    PRINT 'Created [analytics].[FailurePredictions]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'analytics' AND TABLE_NAME = 'GrowthTrends')
BEGIN
    CREATE TABLE [analytics].[GrowthTrends] (
    [TrendId] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NULL,
    [PeriodDays] int NULL,
    [StartSizeMB] decimal(18,2) NULL,
    [EndSizeMB] decimal(18,2) NULL,
    [GrowthMB] decimal(18,2) NULL,
    [GrowthPercent] decimal(10,2) NULL,
    [AvgDailyGrowthMB] decimal(18,4) NULL,
    [TrendType] nvarchar(40) NULL,
    [AnalyzedAt] datetime2 NULL DEFAULT (getdate())
    );
    PRINT 'Created [analytics].[GrowthTrends]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'analytics' AND TABLE_NAME = 'PredictionLog')
BEGIN
    CREATE TABLE [analytics].[PredictionLog] (
    [LogId] int NOT NULL IDENTITY(1,1),
    [PredictionType] nvarchar(100) NULL,
    [PredictionTime] datetime2 NULL DEFAULT (getdate()),
    [ServerName] nvarchar(256) NULL,
    [Summary] nvarchar(1000) NULL,
    [CriticalCount] int NULL,
    [WarningCount] int NULL,
    [Details] nvarchar(MAX) NULL
    );
    PRINT 'Created [analytics].[PredictionLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'analytics' AND TABLE_NAME = 'RemediationLog')
BEGIN
    CREATE TABLE [analytics].[RemediationLog] (
    [LogId] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [IssueType] nvarchar(200) NULL,
    [ActionTaken] nvarchar(1000) NULL,
    [Status] nvarchar(40) NULL,
    [ExecutedAt] datetime2 NULL DEFAULT (getdate()),
    [ExecutedBy] nvarchar(256) NULL,
    [ResultMessage] nvarchar(1000) NULL
    );
    PRINT 'Created [analytics].[RemediationLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'api' AND TABLE_NAME = 'APIKeys')
BEGIN
    CREATE TABLE [api].[APIKeys] (
    [APIKeyID] int NOT NULL IDENTITY(1,1),
    [KeyName] nvarchar(256) NOT NULL,
    [KeyValue] varchar(256) NOT NULL,
    [UserName] nvarchar(256) NOT NULL,
    [IsActive] bit NOT NULL DEFAULT ((1)),
    [CreatedDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [api].[APIKeys]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'app' AND TABLE_NAME = 'ApplicationDatabaseMap')
BEGIN
    CREATE TABLE [app].[ApplicationDatabaseMap] (
    [MapID] int NOT NULL IDENTITY(1,1),
    [ApplicationID] int NOT NULL,
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [ConnectionType] nvarchar(100) NULL,
    [IsProduction] bit NOT NULL DEFAULT ((1)),
    [CreatedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [app].[ApplicationDatabaseMap]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'app' AND TABLE_NAME = 'ApplicationInventory')
BEGIN
    CREATE TABLE [app].[ApplicationInventory] (
    [ApplicationID] int NOT NULL IDENTITY(1,1),
    [ApplicationName] nvarchar(512) NOT NULL,
    [ApplicationCode] nvarchar(100) NULL,
    [Description] nvarchar(MAX) NULL,
    [BusinessUnit] nvarchar(400) NULL,
    [ApplicationOwner] nvarchar(256) NULL,
    [TechnicalOwner] nvarchar(256) NULL,
    [Criticality] nvarchar(40) NULL,
    [Status] nvarchar(100) NOT NULL DEFAULT ('Active'),
    [CreatedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [app].[ApplicationInventory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'app' AND TABLE_NAME = 'DatabaseDependencies')
BEGIN
    CREATE TABLE [app].[DatabaseDependencies] (
    [DependencyID] int NOT NULL IDENTITY(1,1),
    [SourceServer] nvarchar(256) NOT NULL,
    [SourceDatabase] nvarchar(256) NOT NULL,
    [TargetServer] nvarchar(256) NOT NULL,
    [TargetDatabase] nvarchar(256) NOT NULL,
    [DependencyType] nvarchar(100) NOT NULL,
    [DiscoveredAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [app].[DatabaseDependencies]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'app' AND TABLE_NAME = 'DowntimeImpact')
BEGIN
    CREATE TABLE [app].[DowntimeImpact] (
    [ImpactID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NULL,
    [DowntimeStart] datetime2 NOT NULL,
    [DowntimeEnd] datetime2 NULL,
    [DurationMinutes] int NULL,
    [DowntimeType] nvarchar(100) NULL,
    [AffectedApplications] nvarchar(MAX) NULL,
    [BusinessImpact] nvarchar(MAX) NULL,
    [IncidentNumber] nvarchar(100) NULL,
    [RecordedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [app].[DowntimeImpact]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Assessment' AND TABLE_NAME = 'ArchitectureFindings')
BEGIN
    CREATE TABLE [Assessment].[ArchitectureFindings] (
    [FindingID] int NOT NULL IDENTITY(1,1),
    [AssessmentDate] datetime2 NULL DEFAULT (sysdatetime()),
    [Category] nvarchar(200) NULL,
    [Finding] nvarchar(1000) NULL,
    [Severity] nvarchar(40) NULL,
    [CurrentState] nvarchar(MAX) NULL,
    [RecommendedState] nvarchar(MAX) NULL,
    [ImpactAnalysis] nvarchar(MAX) NULL,
    [ImplementationScript] nvarchar(MAX) NULL,
    [Priority] int NULL,
    [EstimatedEffortHours] decimal(5,2) NULL,
    [Status] nvarchar(100) NULL DEFAULT ('Open'),
    [SubCategory] nvarchar(200) NULL
    );
    PRINT 'Created [Assessment].[ArchitectureFindings]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Assessment' AND TABLE_NAME = 'ArchitectureMetrics')
BEGIN
    CREATE TABLE [Assessment].[ArchitectureMetrics] (
    [MetricID] int NOT NULL IDENTITY(1,1),
    [AssessmentDate] datetime2 NULL DEFAULT (sysdatetime()),
    [MetricCategory] nvarchar(200) NULL,
    [MetricName] nvarchar(400) NULL,
    [CurrentValue] nvarchar(1000) NULL,
    [TargetValue] nvarchar(1000) NULL,
    [CompliancePercentage] decimal(5,2) NULL
    );
    PRINT 'Created [Assessment].[ArchitectureMetrics]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Assessment' AND TABLE_NAME = 'ArchitectureStandards')
BEGIN
    CREATE TABLE [Assessment].[ArchitectureStandards] (
    [StandardID] int NOT NULL IDENTITY(1,1),
    [StandardName] nvarchar(510) NOT NULL,
    [StandardCategory] nvarchar(200) NULL,
    [StandardDescription] nvarchar(MAX) NULL,
    [ValidationQuery] nvarchar(MAX) NULL,
    [IsActive] bit NULL DEFAULT ((1))
    );
    PRINT 'Created [Assessment].[ArchitectureStandards]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Assessment' AND TABLE_NAME = 'AssessmentHistory')
BEGIN
    CREATE TABLE [Assessment].[AssessmentHistory] (
    [HistoryID] int NOT NULL IDENTITY(1,1),
    [AssessmentDate] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [MaturityScore] decimal(5,2) NULL,
    [MaturityLevel] nvarchar(100) NULL,
    [TotalFindings] int NULL,
    [CriticalFindings] int NULL,
    [HighFindings] int NULL,
    [MediumFindings] int NULL,
    [LowFindings] int NULL,
    [TotalSchemas] int NULL,
    [TotalTables] int NULL,
    [TotalStoredProcs] int NULL,
    [TotalViews] int NULL,
    [TotalJobs] int NULL,
    [TotalLinkedServers] int NULL,
    [DatabaseSizeMB] decimal(18,2) NULL,
    [TotalRowCount] bigint NULL,
    [EstimatedEffortHours] decimal(10,2) NULL,
    [NotificationSent] bit NULL DEFAULT ((0)),
    [NotificationTime] datetime2 NULL,
    [ExecutionDurationSeconds] int NULL
    );
    PRINT 'Created [Assessment].[AssessmentHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Assessment' AND TABLE_NAME = 'AssessmentResults')
BEGIN
    CREATE TABLE [Assessment].[AssessmentResults] (
    [ResultID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(510) NOT NULL,
    [RuleID] int NOT NULL,
    [IsCompliant] bit NOT NULL,
    [FindingDetails] nvarchar(MAX) NULL,
    [AssessmentDate] datetime NULL DEFAULT (getdate()),
    [ResolvedDate] datetime NULL,
    [ResolvedBy] nvarchar(256) NULL
    );
    PRINT 'Created [Assessment].[AssessmentResults]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Assessment' AND TABLE_NAME = 'AssessmentRuns')
BEGIN
    CREATE TABLE [Assessment].[AssessmentRuns] (
    [RunID] int NOT NULL IDENTITY(1,1),
    [RunDate] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [ServerName] sysname NOT NULL,
    [Status] varchar(20) NOT NULL,
    [CriticalCount] int NOT NULL DEFAULT ((0)),
    [HighCount] int NOT NULL DEFAULT ((0)),
    [MediumCount] int NOT NULL DEFAULT ((0)),
    [LowCount] int NOT NULL DEFAULT ((0)),
    [MaturityScore] decimal(5,2) NULL,
    [Notes] nvarchar(1000) NULL
    );
    PRINT 'Created [Assessment].[AssessmentRuns]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Assessment' AND TABLE_NAME = 'AssessmentSummary')
BEGIN
    CREATE TABLE [Assessment].[AssessmentSummary] (
    [SummaryID] int NOT NULL IDENTITY(1,1),
    [AssessmentDate] datetime2 NULL DEFAULT (sysdatetime()),
    [ServerName] nvarchar(256) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [TotalSchemas] int NULL,
    [TotalTables] int NULL,
    [TotalStoredProcs] int NULL,
    [TotalViews] int NULL,
    [TotalFunctions] int NULL,
    [TotalTriggers] int NULL,
    [TotalJobs] int NULL,
    [TotalLinkedServers] int NULL,
    [CriticalFindings] int NULL,
    [HighFindings] int NULL,
    [MediumFindings] int NULL,
    [LowFindings] int NULL,
    [MaturityScore] decimal(5,2) NULL,
    [MaturityLevel] nvarchar(100) NULL,
    [TotalEstimatedEffortHours] decimal(10,2) NULL,
    [DatabaseSizeMB] decimal(18,2) NULL,
    [TotalRowCount] bigint NULL
    );
    PRINT 'Created [Assessment].[AssessmentSummary]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Assessment' AND TABLE_NAME = 'ComplianceControlResults')
BEGIN
    CREATE TABLE [Assessment].[ComplianceControlResults] (
    [ResultID] int NOT NULL IDENTITY(1,1),
    [AssessmentDate] datetime2 NULL DEFAULT (sysdatetime()),
    [ControlID] int NULL,
    [FrameworkCode] varchar(20) NULL,
    [ControlCode] varchar(50) NULL,
    [ServerName] varchar(128) NULL,
    [ControlStatus] varchar(20) NULL,
    [Finding] nvarchar(MAX) NULL,
    [Evidence] nvarchar(MAX) NULL,
    [RemediationRequired] bit NULL DEFAULT ((0))
    );
    PRINT 'Created [Assessment].[ComplianceControlResults]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Assessment' AND TABLE_NAME = 'ComplianceControls')
BEGIN
    CREATE TABLE [Assessment].[ComplianceControls] (
    [ControlID] int NOT NULL IDENTITY(1,1),
    [FrameworkID] int NULL,
    [ControlCode] varchar(50) NOT NULL,
    [ControlName] varchar(200) NOT NULL,
    [ControlDescription] nvarchar(2000) NULL,
    [Category] varchar(50) NULL,
    [Severity] varchar(20) NULL DEFAULT ('MEDIUM'),
    [ControlWeight] int NULL DEFAULT ((1)),
    [CheckQuery] nvarchar(MAX) NULL,
    [RemediationSteps] nvarchar(MAX) NULL,
    [IsAutomated] bit NULL DEFAULT ((1)),
    [IsActive] bit NULL DEFAULT ((1))
    );
    PRINT 'Created [Assessment].[ComplianceControls]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Assessment' AND TABLE_NAME = 'ComplianceFrameworks')
BEGIN
    CREATE TABLE [Assessment].[ComplianceFrameworks] (
    [FrameworkID] int NOT NULL IDENTITY(1,1),
    [FrameworkCode] varchar(20) NOT NULL,
    [FrameworkName] varchar(100) NOT NULL,
    [FrameworkDescription] nvarchar(1000) NULL,
    [FrameworkVersion] varchar(20) NULL,
    [IsActive] bit NULL DEFAULT ((1)),
    [CreatedDate] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [Assessment].[ComplianceFrameworks]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Assessment' AND TABLE_NAME = 'ComplianceRules')
BEGIN
    CREATE TABLE [Assessment].[ComplianceRules] (
    [RuleID] int NOT NULL IDENTITY(1,1),
    [RuleName] nvarchar(510) NOT NULL,
    [RuleCategory] nvarchar(200) NOT NULL,
    [RuleDescription] nvarchar(MAX) NULL,
    [Severity] nvarchar(40) NOT NULL,
    [Weight] int NULL DEFAULT ((1)),
    [CheckQuery] nvarchar(MAX) NULL,
    [RemediationSteps] nvarchar(MAX) NULL,
    [IsActive] bit NULL DEFAULT ((1)),
    [CreatedDate] datetime NULL DEFAULT (getdate()),
    [ModifiedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [Assessment].[ComplianceRules]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Assessment' AND TABLE_NAME = 'ComplianceScoreHistory')
BEGIN
    CREATE TABLE [Assessment].[ComplianceScoreHistory] (
    [ScoreID] int NOT NULL IDENTITY(1,1),
    [AssessmentDate] datetime2 NULL DEFAULT (sysdatetime()),
    [FrameworkCode] varchar(20) NULL,
    [TotalControls] int NULL,
    [PassedControls] int NULL,
    [FailedControls] int NULL,
    [NotApplicable] int NULL,
    [ComplianceScore] decimal(5,2) NULL,
    [ComplianceGrade] varchar(2) NULL,
    [PreviousScore] decimal(5,2) NULL,
    [ScoreChange] decimal(5,2) NULL,
    [AssessedBy] varchar(100) NULL DEFAULT (suser_sname())
    );
    PRINT 'Created [Assessment].[ComplianceScoreHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Assessment' AND TABLE_NAME = 'Configuration')
BEGIN
    CREATE TABLE [Assessment].[Configuration] (
    [ConfigID] int NOT NULL IDENTITY(1,1),
    [ConfigKey] nvarchar(200) NOT NULL,
    [ConfigValue] nvarchar(MAX) NULL,
    [Description] nvarchar(1000) NULL,
    [LastModified] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [Assessment].[Configuration]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Assessment' AND TABLE_NAME = 'DailyStatusSummary')
BEGIN
    CREATE TABLE [Assessment].[DailyStatusSummary] (
    [StatusID] int NOT NULL IDENTITY(1,1),
    [RunDate] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [ServerName] sysname NOT NULL,
    [StatusMessage] nvarchar(2000) NOT NULL
    );
    PRINT 'Created [Assessment].[DailyStatusSummary]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Assessment' AND TABLE_NAME = 'ServerComplianceScores')
BEGIN
    CREATE TABLE [Assessment].[ServerComplianceScores] (
    [ScoreID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(510) NOT NULL,
    [OverallScore] decimal(5,2) NULL,
    [SecurityScore] decimal(5,2) NULL,
    [PerformanceScore] decimal(5,2) NULL,
    [BackupScore] decimal(5,2) NULL,
    [ConfigurationScore] decimal(5,2) NULL,
    [ArchitectureScore] decimal(5,2) NULL,
    [CriticalFindings] int NULL DEFAULT ((0)),
    [HighFindings] int NULL DEFAULT ((0)),
    [MediumFindings] int NULL DEFAULT ((0)),
    [LowFindings] int NULL DEFAULT ((0)),
    [ScoreDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [Assessment].[ServerComplianceScores]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'audit' AND TABLE_NAME = 'AuditDailySummary')
BEGIN
    CREATE TABLE [audit].[AuditDailySummary] (
    [SummaryDate] date NOT NULL,
    [TotalEvents] int NOT NULL,
    [FailedLogins] int NOT NULL,
    [SuccessfulLogins] int NOT NULL,
    [ServerCount] int NOT NULL,
    [InsertDate] datetime NOT NULL DEFAULT (getdate())
    );
    PRINT 'Created [audit].[AuditDailySummary]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'audit' AND TABLE_NAME = 'AuditLog')
BEGIN
    CREATE TABLE [audit].[AuditLog] (
    [AuditID] bigint NOT NULL IDENTITY(1,1),
    [EventTime] datetime2 NULL DEFAULT (sysutcdatetime()),
    [LoginName] sysname NOT NULL,
    [HostName] sysname NOT NULL,
    [ActionType] varchar(50) NULL,
    [ObjectName] varchar(200) NULL,
    [ObjectType] varchar(50) NULL,
    [TSQLCommand] nvarchar(MAX) NULL
    );
    PRINT 'Created [audit].[AuditLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'audit' AND TABLE_NAME = 'AuditSummary')
BEGIN
    CREATE TABLE [audit].[AuditSummary] (
    [SummaryID] int NOT NULL IDENTITY(1,1),
    [SummaryDate] date NOT NULL DEFAULT (CONVERT([date],getdate())),
    [TotalLoginsFailed] int NULL,
    [TotalLoginsSucceeded] int NULL,
    [TotalPasswordChanges] int NULL,
    [TotalServerRestarts] int NULL,
    [TotalAgentFailures] int NULL,
    [TotalSeverityErrors] int NULL,
    [TotalDeadlocks] int NULL,
    [InsertedAt] datetime NOT NULL DEFAULT (getdate())
    );
    PRINT 'Created [audit].[AuditSummary]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'audit' AND TABLE_NAME = 'BlockingEvents')
BEGIN
    CREATE TABLE [audit].[BlockingEvents] (
    [BlockingID] int NOT NULL IDENTITY(1,1),
    [ServerName] varchar(256) NOT NULL,
    [EventTime] datetime2 NULL DEFAULT (sysdatetime()),
    [BlockedSPID] int NULL,
    [BlockedLoginName] nvarchar(512) NULL,
    [BlockedHostName] nvarchar(512) NULL,
    [BlockedDatabase] nvarchar(512) NULL,
    [BlockedWaitTime] int NULL,
    [BlockedCommand] nvarchar(MAX) NULL,
    [BlockedSQL] nvarchar(MAX) NULL,
    [BlockingSPID] int NULL,
    [BlockingLoginName] nvarchar(512) NULL,
    [BlockingHostName] nvarchar(512) NULL,
    [BlockingDatabase] nvarchar(512) NULL,
    [BlockingCommand] nvarchar(MAX) NULL,
    [BlockingSQL] nvarchar(MAX) NULL,
    [CollectedAt] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [audit].[BlockingEvents]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'audit' AND TABLE_NAME = 'ComplianceCheckResults')
BEGIN
    CREATE TABLE [audit].[ComplianceCheckResults] (
    [CheckID] bigint NOT NULL IDENTITY(1,1),
    [CheckDate] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [ServerName] nvarchar(512) NOT NULL,
    [Framework] nvarchar(100) NOT NULL,
    [ControlID] nvarchar(100) NOT NULL,
    [ControlName] nvarchar(512) NOT NULL,
    [Status] nvarchar(40) NOT NULL,
    [Finding] nvarchar(MAX) NULL,
    [Recommendation] nvarchar(MAX) NULL,
    [Severity] nvarchar(40) NULL
    );
    PRINT 'Created [audit].[ComplianceCheckResults]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'audit' AND TABLE_NAME = 'DataCleanupLog')
BEGIN
    CREATE TABLE [audit].[DataCleanupLog] (
    [CleanupLogID] int NOT NULL IDENTITY(1,1),
    [CleanupProcedure] sysname NOT NULL,
    [RowsDeleted] bigint NOT NULL,
    [CutoffDate] datetime NOT NULL,
    [RunDate] datetime NOT NULL
    );
    PRINT 'Created [audit].[DataCleanupLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'audit' AND TABLE_NAME = 'DeadlockEvents')
BEGIN
    CREATE TABLE [audit].[DeadlockEvents] (
    [ServerName] varchar(256) NOT NULL,
    [EventTime] datetime2 NULL DEFAULT (sysdatetime()),
    [DeadlockGraph] xml NULL,
    [VictimSPID] int NULL,
    [VictimLoginName] nvarchar(512) NULL,
    [VictimHostName] nvarchar(512) NULL,
    [VictimDatabase] nvarchar(512) NULL,
    [CollectedAt] datetime2 NULL DEFAULT (sysdatetime()),
    [DeadlockID] uniqueidentifier NOT NULL DEFAULT (newid()),
    [DeadlockUID] uniqueidentifier NULL DEFAULT (newid())
    );
    PRINT 'Created [audit].[DeadlockEvents]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'audit' AND TABLE_NAME = 'DeadlockThresholdLog')
BEGIN
    CREATE TABLE [audit].[DeadlockThresholdLog] (
    [ID] int NOT NULL IDENTITY(1,1),
    [ServerName] sysname NOT NULL,
    [DeadlockCount] int NULL,
    [Severity] varchar(20) NULL,
    [LoggedAt] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [audit].[DeadlockThresholdLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'audit' AND TABLE_NAME = 'DeadlockThresholds')
BEGIN
    CREATE TABLE [audit].[DeadlockThresholds] (
    [ServerName] sysname NOT NULL,
    [WarningThreshold] int NOT NULL DEFAULT ((5)),
    [CriticalThreshold] int NOT NULL DEFAULT ((10)),
    [LastAlertedAt] datetime2 NULL
    );
    PRINT 'Created [audit].[DeadlockThresholds]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'audit' AND TABLE_NAME = 'fact_UserActions')
BEGIN
    CREATE TABLE [audit].[fact_UserActions] (
    [ActionID] bigint NOT NULL IDENTITY(1,1),
    [UserName] nvarchar(200) NOT NULL,
    [UserEmail] nvarchar(400) NULL,
    [ADGroups] nvarchar(MAX) NULL,
    [PrimaryRole] nvarchar(100) NULL,
    [ActionType] nvarchar(100) NOT NULL,
    [ActionCategory] nvarchar(100) NOT NULL,
    [ActionTarget] nvarchar(400) NULL,
    [ActionDetails] nvarchar(MAX) NULL,
    [BeforeState] nvarchar(MAX) NULL,
    [AfterState] nvarchar(MAX) NULL,
    [IPAddress] nvarchar(100) NULL,
    [UserAgent] nvarchar(1000) NULL,
    [ActionTime] datetime2 NOT NULL DEFAULT (getdate()),
    [Success] bit NOT NULL DEFAULT ((1)),
    [ErrorMessage] nvarchar(MAX) NULL,
    [ExecutionTimeMS] int NULL,
    [SessionID] nvarchar(200) NULL
    );
    PRINT 'Created [audit].[fact_UserActions]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'audit' AND TABLE_NAME = 'LinkedServerBuildLog')
BEGIN
    CREATE TABLE [audit].[LinkedServerBuildLog] (
    [ID] int NOT NULL IDENTITY(1,1),
    [ServerName] varchar(200) NULL,
    [InstanceName] varchar(200) NULL,
    [FullInstance] varchar(300) NULL,
    [ActionTaken] varchar(200) NULL,
    [ActionTime] datetime NULL DEFAULT (getdate()),
    [Status] varchar(50) NULL,
    [ErrorMessage] varchar(MAX) NULL
    );
    PRINT 'Created [audit].[LinkedServerBuildLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'audit' AND TABLE_NAME = 'LoginBaseline')
BEGIN
    CREATE TABLE [audit].[LoginBaseline] (
    [BaselineID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [LoginName] nvarchar(256) NULL,
    [LoginType] nvarchar(100) NULL,
    [IsDisabled] bit NULL,
    [DefaultDatabase] nvarchar(256) NULL,
    [CollectedAt] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [audit].[LoginBaseline]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'audit' AND TABLE_NAME = 'LoginChanges')
BEGIN
    CREATE TABLE [audit].[LoginChanges] (
    [AuditID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [LoginName] nvarchar(256) NULL,
    [ChangeType] nvarchar(200) NULL,
    [DefaultDB] nvarchar(256) NULL,
    [SID] varbinary NULL,
    [EventTime] datetime2 NULL,
    [InitiatorLogin] nvarchar(256) NULL,
    [InsertedOn] datetime2 NULL DEFAULT (sysutcdatetime())
    );
    PRINT 'Created [audit].[LoginChanges]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'audit' AND TABLE_NAME = 'LoginDrift')
BEGIN
    CREATE TABLE [audit].[LoginDrift] (
    [DriftID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [LoginName] nvarchar(256) NULL,
    [LoginType] nvarchar(100) NULL,
    [IsDisabled] bit NULL,
    [DriftType] nvarchar(40) NULL,
    [DetectedAt] datetime NULL DEFAULT (getdate()),
    [Acknowledged] bit NULL DEFAULT ((0))
    );
    PRINT 'Created [audit].[LoginDrift]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'audit' AND TABLE_NAME = 'LoginFailures')
BEGIN
    CREATE TABLE [audit].[LoginFailures] (
    [EventID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [LoginName] nvarchar(256) NULL,
    [EventTime] datetime NULL,
    [ErrorMessage] nvarchar(8000) NULL,
    [FailedHost] nvarchar(256) NULL,
    [Application] nvarchar(512) NULL,
    [ClientHost] nvarchar(512) NULL
    );
    PRINT 'Created [audit].[LoginFailures]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'audit' AND TABLE_NAME = 'ObjectChanges')
BEGIN
    CREATE TABLE [audit].[ObjectChanges] (
    [AuditID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [SchemaName] nvarchar(256) NULL,
    [ObjectName] nvarchar(512) NULL,
    [ObjectType] nvarchar(120) NULL,
    [EventType] nvarchar(200) NULL,
    [DDLCommand] nvarchar(MAX) NULL,
    [EventTime] datetime2 NULL,
    [LoginName] nvarchar(256) NULL,
    [UserName] nvarchar(256) NULL,
    [SPID] int NULL,
    [HostName] nvarchar(256) NULL,
    [ApplicationName] nvarchar(512) NULL,
    [InsertedOn] datetime2 NULL DEFAULT (sysutcdatetime()),
    [ChangedBy] nvarchar(512) NULL,
    [CommandText] nvarchar(MAX) NULL
    );
    PRINT 'Created [audit].[ObjectChanges]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'audit' AND TABLE_NAME = 'PermissionBaseline')
BEGIN
    CREATE TABLE [audit].[PermissionBaseline] (
    [BaselineID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [PrincipalName] nvarchar(256) NULL,
    [PrincipalType] nvarchar(100) NULL,
    [Permission] nvarchar(256) NULL,
    [PermissionState] nvarchar(100) NULL,
    [Scope] nvarchar(100) NULL,
    [CollectedAt] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [audit].[PermissionBaseline]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'audit' AND TABLE_NAME = 'PermissionChanges')
BEGIN
    CREATE TABLE [audit].[PermissionChanges] (
    [LogID] int NOT NULL IDENTITY(1,1),
    [ServerName] varchar(100) NOT NULL,
    [Permission] varchar(205) NOT NULL,
    [ChangeTime] datetime NOT NULL,
    [UserName] varchar(128) NOT NULL,
    [ChangedBy] nvarchar(256) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [EventTime] datetime NULL DEFAULT (getdate()),
    [ObjectName] nvarchar(512) NULL,
    [ChangeType] nvarchar(100) NULL,
    [CommandText] nvarchar(MAX) NULL
    );
    PRINT 'Created [audit].[PermissionChanges]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'audit' AND TABLE_NAME = 'PermissionDrift')
BEGIN
    CREATE TABLE [audit].[PermissionDrift] (
    [DriftID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [PrincipalName] nvarchar(256) NULL,
    [PrincipalType] nvarchar(100) NULL,
    [Permission] nvarchar(256) NULL,
    [PermissionState] nvarchar(100) NULL,
    [Scope] nvarchar(100) NULL,
    [DriftType] nvarchar(40) NULL,
    [DetectedAt] datetime NULL DEFAULT (getdate()),
    [Acknowledged] bit NULL DEFAULT ((0))
    );
    PRINT 'Created [audit].[PermissionDrift]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'audit' AND TABLE_NAME = 'PHIAccessLog')
BEGIN
    CREATE TABLE [audit].[PHIAccessLog] (
    [AccessID] bigint NOT NULL IDENTITY(1,1),
    [ServerID] int NOT NULL,
    [UserName] nvarchar(256) NOT NULL,
    [AccessType] nvarchar(120) NOT NULL,
    [AccessDateTime] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [audit].[PHIAccessLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'audit' AND TABLE_NAME = 'ServiceAccountUsage')
BEGIN
    CREATE TABLE [audit].[ServiceAccountUsage] (
    [UsageID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(512) NOT NULL,
    [ServiceAccount] nvarchar(512) NOT NULL,
    [LoginName] nvarchar(512) NULL,
    [HostName] nvarchar(512) NULL,
    [ApplicationName] nvarchar(512) NULL,
    [DatabaseName] nvarchar(512) NULL,
    [EventType] nvarchar(100) NOT NULL,
    [EventTime] datetime2 NOT NULL,
    [ClientIP] nvarchar(100) NULL,
    [CommandText] nvarchar(MAX) NULL,
    [CollectedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [audit].[ServiceAccountUsage]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'automation' AND TABLE_NAME = 'PendingApproval')
BEGIN
    CREATE TABLE [automation].[PendingApproval] (
    [ApprovalID] bigint NOT NULL IDENTITY(1,1),
    [RuleID] int NOT NULL,
    [ServerName] nvarchar(256) NOT NULL,
    [RequestedAction] nvarchar(MAX) NULL,
    [RequestedAt] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [ExpiresAt] datetime2 NULL,
    [Status] nvarchar(100) NOT NULL DEFAULT ('Pending'),
    [ReviewedBy] nvarchar(256) NULL,
    [ReviewedAt] datetime2 NULL
    );
    PRINT 'Created [automation].[PendingApproval]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'automation' AND TABLE_NAME = 'RemediationLog')
BEGIN
    CREATE TABLE [automation].[RemediationLog] (
    [LogID] bigint NOT NULL IDENTITY(1,1),
    [RuleID] int NOT NULL,
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NULL,
    [ActionTaken] nvarchar(MAX) NULL,
    [ExecutionStart] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [ExecutionEnd] datetime2 NULL,
    [DurationMs] int NULL,
    [Status] nvarchar(100) NOT NULL,
    [ResultMessage] nvarchar(MAX) NULL,
    [ErrorMessage] nvarchar(MAX) NULL
    );
    PRINT 'Created [automation].[RemediationLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'automation' AND TABLE_NAME = 'RemediationRule')
BEGIN
    CREATE TABLE [automation].[RemediationRule] (
    [RuleID] int NOT NULL IDENTITY(1,1),
    [RuleName] nvarchar(400) NOT NULL,
    [RuleCategory] nvarchar(200) NOT NULL,
    [Description] nvarchar(1000) NULL,
    [TriggerCondition] nvarchar(MAX) NULL,
    [RemediationAction] nvarchar(MAX) NULL,
    [ActionType] nvarchar(100) NOT NULL,
    [RequiresApproval] bit NOT NULL DEFAULT ((0)),
    [MaxExecutionsPerHour] int NULL DEFAULT ((3)),
    [CooldownMinutes] int NULL DEFAULT ((30)),
    [IsEnabled] bit NOT NULL DEFAULT ((1)),
    [RiskLevel] nvarchar(40) NULL,
    [CreatedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [automation].[RemediationRule]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'automation' AND TABLE_NAME = 'ServiceRestartHistory')
BEGIN
    CREATE TABLE [automation].[ServiceRestartHistory] (
    [RestartID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [ServiceName] nvarchar(512) NOT NULL,
    [RestartReason] nvarchar(1000) NULL,
    [InitiatedBy] nvarchar(100) NOT NULL,
    [RestartStartTime] datetime2 NOT NULL,
    [RestartEndTime] datetime2 NULL,
    [Status] nvarchar(100) NOT NULL,
    [ErrorMessage] nvarchar(MAX) NULL
    );
    PRINT 'Created [automation].[ServiceRestartHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'baseline' AND TABLE_NAME = 'DatabaseRoleMembers')
BEGIN
    CREATE TABLE [baseline].[DatabaseRoleMembers] (
    [CaptureDate] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [RoleName] nvarchar(256) NOT NULL,
    [MemberName] nvarchar(256) NOT NULL
    );
    PRINT 'Created [baseline].[DatabaseRoleMembers]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'baseline' AND TABLE_NAME = 'DatabaseUsers')
BEGIN
    CREATE TABLE [baseline].[DatabaseUsers] (
    [CaptureDate] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [UserName] nvarchar(256) NOT NULL,
    [LoginName] nvarchar(256) NULL,
    [DefaultSchema] nvarchar(256) NULL
    );
    PRINT 'Created [baseline].[DatabaseUsers]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'baseline' AND TABLE_NAME = 'ServerLogins')
BEGIN
    CREATE TABLE [baseline].[ServerLogins] (
    [CaptureDate] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [ServerName] nvarchar(256) NOT NULL,
    [LoginName] nvarchar(256) NOT NULL,
    [LoginType] varchar(20) NULL,
    [IsDisabled] bit NULL,
    [CreateDate] datetime NULL,
    [ModifyDate] datetime NULL,
    [DefaultDatabase] nvarchar(256) NULL,
    [DefaultLanguage] nvarchar(256) NULL,
    [HashedPassword] varbinary NULL,
    [PasswordHash] varchar(MAX) NULL,
    [SID] varbinary NULL,
    [IsSystemObject] bit NULL
    );
    PRINT 'Created [baseline].[ServerLogins]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'baseline' AND TABLE_NAME = 'ServerPermissions')
BEGIN
    CREATE TABLE [baseline].[ServerPermissions] (
    [CaptureDate] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [ServerName] nvarchar(256) NOT NULL,
    [GranteeName] nvarchar(256) NOT NULL,
    [PermissionName] nvarchar(256) NOT NULL,
    [State] varchar(20) NULL
    );
    PRINT 'Created [baseline].[ServerPermissions]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'baseline' AND TABLE_NAME = 'ServerRoleMembers')
BEGIN
    CREATE TABLE [baseline].[ServerRoleMembers] (
    [CaptureDate] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [ServerName] nvarchar(256) NOT NULL,
    [RoleName] nvarchar(256) NOT NULL,
    [MemberName] nvarchar(256) NOT NULL
    );
    PRINT 'Created [baseline].[ServerRoleMembers]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bkp' AND TABLE_NAME = 'BackupComplianceStatus')
BEGIN
    CREATE TABLE [bkp].[BackupComplianceStatus] (
    [ComplianceID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [RecoveryModel] nvarchar(120) NULL,
    [LastFullBackup] datetime2 NULL,
    [LastDiffBackup] datetime2 NULL,
    [LastLogBackup] datetime2 NULL,
    [FullBackupAgeHours] int NULL,
    [IsFullCompliant] bit NULL,
    [IsDiffCompliant] bit NULL,
    [IsLogCompliant] bit NULL,
    [OverallCompliant] bit NULL,
    [ComplianceScore] decimal(5,2) NULL,
    [EvaluatedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [bkp].[BackupComplianceStatus]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bkp' AND TABLE_NAME = 'BackupHistory')
BEGIN
    CREATE TABLE [bkp].[BackupHistory] (
    [BackupHistoryID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [BackupType] char(1) NOT NULL,
    [BackupStartDate] datetime2 NOT NULL,
    [BackupFinishDate] datetime2 NULL,
    [DurationSeconds] int NULL,
    [BackupSizeMB] decimal(18,2) NULL,
    [CompressedSizeMB] decimal(18,2) NULL,
    [BackupPath] nvarchar(1000) NULL,
    [BackupSource] nvarchar(100) NULL,
    [CollectedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [bkp].[BackupHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bkp' AND TABLE_NAME = 'BackupSLAConfig')
BEGIN
    CREATE TABLE [bkp].[BackupSLAConfig] (
    [SLAConfigID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [DatabaseTier] nvarchar(100) NULL,
    [FullBackupMaxAgeHours] int NOT NULL DEFAULT ((168)),
    [DiffBackupMaxAgeHours] int NULL DEFAULT ((24)),
    [LogBackupMaxAgeMinutes] int NULL DEFAULT ((15)),
    [RPOMinutes] int NOT NULL DEFAULT ((15)),
    [RTOMinutes] int NOT NULL DEFAULT ((60)),
    [IsEnabled] bit NOT NULL DEFAULT ((1))
    );
    PRINT 'Created [bkp].[BackupSLAConfig]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bkp' AND TABLE_NAME = 'RestoreTestHistory')
BEGIN
    CREATE TABLE [bkp].[RestoreTestHistory] (
    [RestoreTestID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [RestoreStartTime] datetime2 NOT NULL,
    [RestoreEndTime] datetime2 NULL,
    [DurationSeconds] int NULL,
    [Status] nvarchar(100) NOT NULL,
    [ValidationPassed] bit NULL,
    [ActualRTOMinutes] int NULL,
    [ErrorMessage] nvarchar(MAX) NULL
    );
    PRINT 'Created [bkp].[RestoreTestHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bkp' AND TABLE_NAME = 'VeeamBackupJobs')
BEGIN
    CREATE TABLE [bkp].[VeeamBackupJobs] (
    [VeeamJobID] bigint NOT NULL IDENTITY(1,1),
    [JobName] nvarchar(512) NOT NULL,
    [ServerName] nvarchar(256) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [Status] nvarchar(100) NULL,
    [StartTime] datetime2 NULL,
    [EndTime] datetime2 NULL,
    [DurationSeconds] int NULL,
    [DataSizeMB] decimal(18,2) NULL,
    [BackupSizeMB] decimal(18,2) NULL,
    [ErrorMessage] nvarchar(MAX) NULL,
    [JSONPayload] nvarchar(MAX) NULL,
    [CollectedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [bkp].[VeeamBackupJobs]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bkp' AND TABLE_NAME = 'VeeamRepository')
BEGIN
    CREATE TABLE [bkp].[VeeamRepository] (
    [RepoID] int NOT NULL IDENTITY(1,1),
    [RepositoryName] nvarchar(512) NOT NULL,
    [TotalSpaceGB] decimal(18,2) NULL,
    [FreeSpaceGB] decimal(18,2) NULL,
    [FreeSpacePercent] decimal(5,2) NULL,
    [IsAvailable] bit NULL,
    [LastChecked] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [bkp].[VeeamRepository]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'capacity' AND TABLE_NAME = 'DatabaseGrowth')
BEGIN
    CREATE TABLE [capacity].[DatabaseGrowth] (
    [GrowthID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(512) NOT NULL,
    [DatabaseName] nvarchar(512) NOT NULL,
    [DataSizeMB] decimal(18,2) NULL,
    [LogSizeMB] decimal(18,2) NULL,
    [DataUsedMB] decimal(18,2) NULL,
    [LogUsedMB] decimal(18,2) NULL,
    [RowCount] bigint NULL,
    [CollectedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [capacity].[DatabaseGrowth]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'capacity' AND TABLE_NAME = 'DatabaseSizeHistory')
BEGIN
    CREATE TABLE [capacity].[DatabaseSizeHistory] (
    [SizeHistoryID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [DataSizeMB] decimal(18,2) NOT NULL,
    [LogSizeMB] decimal(18,2) NOT NULL,
    [TotalSizeMB] decimal(18,2) NOT NULL,
    [RecordCount] bigint NULL,
    [CollectedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [capacity].[DatabaseSizeHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'capacity' AND TABLE_NAME = 'DiskSpaceHistory')
BEGIN
    CREATE TABLE [capacity].[DiskSpaceHistory] (
    [DiskSpaceID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DriveLetter] char(1) NOT NULL,
    [TotalSpaceGB] decimal(18,2) NOT NULL,
    [FreeSpaceGB] decimal(18,2) NOT NULL,
    [UsedSpaceGB] decimal(18,2) NOT NULL,
    [FreeSpacePercent] decimal(5,2) NOT NULL,
    [CollectedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [capacity].[DiskSpaceHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'capacity' AND TABLE_NAME = 'GrowthForecast')
BEGIN
    CREATE TABLE [capacity].[GrowthForecast] (
    [ForecastID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [ResourceType] nvarchar(100) NOT NULL,
    [ResourceName] nvarchar(512) NOT NULL,
    [CurrentSizeGB] decimal(18,2) NOT NULL,
    [DailyGrowthGB] decimal(18,4) NULL,
    [MonthlyGrowthGB] decimal(18,4) NULL,
    [ThresholdGB] decimal(18,2) NULL,
    [DaysToThreshold] int NULL,
    [ProjectedDateAtThreshold] date NULL,
    [ConfidencePercent] decimal(5,2) NULL,
    [CalculatedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [capacity].[GrowthForecast]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'capacity' AND TABLE_NAME = 'ResourceUtilization')
BEGIN
    CREATE TABLE [capacity].[ResourceUtilization] (
    [UtilizationID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(512) NOT NULL,
    [CPUPercent] decimal(5,2) NULL,
    [MemoryPercent] decimal(5,2) NULL,
    [DiskIOPercent] decimal(5,2) NULL,
    [NetworkPercent] decimal(5,2) NULL,
    [CollectedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [capacity].[ResourceUtilization]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'capacity' AND TABLE_NAME = 'StorageForecasts')
BEGIN
    CREATE TABLE [capacity].[StorageForecasts] (
    [ForecastID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(512) NOT NULL,
    [DriveLetter] char(1) NOT NULL,
    [CurrentSizeGB] decimal(18,2) NULL,
    [CurrentUsedGB] decimal(18,2) NULL,
    [GrowthRateGBPerDay] decimal(18,4) NULL,
    [PredictedFullDate] date NULL,
    [ConfidenceLevel] decimal(5,2) NULL,
    [ForecastDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [capacity].[StorageForecasts]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'capacity' AND TABLE_NAME = 'TableSizeHistory')
BEGIN
    CREATE TABLE [capacity].[TableSizeHistory] (
    [TableSizeID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [SchemaName] nvarchar(256) NOT NULL,
    [TableName] nvarchar(512) NOT NULL,
    [RecordCount] bigint NOT NULL,
    [TotalSpaceMB] decimal(18,2) NOT NULL,
    [DataSpaceMB] decimal(18,2) NOT NULL,
    [IndexSpaceMB] decimal(18,2) NOT NULL,
    [CollectedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [capacity].[TableSizeHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'change' AND TABLE_NAME = 'ChangeTypes')
BEGIN
    CREATE TABLE [change].[ChangeTypes] (
    [ChangeTypeID] int NOT NULL IDENTITY(1,1),
    [ChangeTypeName] nvarchar(200) NOT NULL,
    [ChangeCategory] nvarchar(100) NOT NULL,
    [Icon] nvarchar(100) NULL,
    [Color] nvarchar(40) NULL,
    [Description] nvarchar(1000) NULL,
    [ImpactLevel] tinyint NULL DEFAULT ((2))
    );
    PRINT 'Created [change].[ChangeTypes]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'change' AND TABLE_NAME = 'ConfigurationChanges')
BEGIN
    CREATE TABLE [change].[ConfigurationChanges] (
    [ChangeID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(512) NOT NULL,
    [ConfigName] nvarchar(512) NOT NULL,
    [OldValue] nvarchar(512) NULL,
    [NewValue] nvarchar(512) NULL,
    [ChangedBy] nvarchar(512) NULL,
    [ChangeTime] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [change].[ConfigurationChanges]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'change' AND TABLE_NAME = 'DDLEvents')
BEGIN
    CREATE TABLE [change].[DDLEvents] (
    [EventID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(512) NOT NULL,
    [DatabaseName] nvarchar(512) NULL,
    [EventType] nvarchar(200) NOT NULL,
    [ObjectName] nvarchar(512) NULL,
    [ObjectType] nvarchar(100) NULL,
    [SchemaName] nvarchar(512) NULL,
    [LoginName] nvarchar(512) NULL,
    [EventTime] datetime NOT NULL,
    [CommandText] nvarchar(MAX) NULL
    );
    PRINT 'Created [change].[DDLEvents]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'change' AND TABLE_NAME = 'DeploymentRegistry')
BEGIN
    CREATE TABLE [change].[DeploymentRegistry] (
    [DeploymentID] bigint NOT NULL IDENTITY(1,1),
    [DeploymentGUID] uniqueidentifier NULL DEFAULT (newid()),
    [ServerName] nvarchar(256) NULL,
    [CMSGroupName] nvarchar(400) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [ApplicationName] nvarchar(400) NULL,
    [Version] nvarchar(100) NULL,
    [PreviousVersion] nvarchar(100) NULL,
    [DeploymentDateTime] datetime2 NULL DEFAULT (getdate()),
    [DeployedBy] nvarchar(200) NULL,
    [DeploymentSource] nvarchar(200) NULL,
    [TicketNumber] nvarchar(100) NULL,
    [ChangeControlNumber] nvarchar(100) NULL,
    [Description] nvarchar(MAX) NULL,
    [Status] nvarchar(100) NULL DEFAULT ('Completed'),
    [RollbackAvailable] bit NULL DEFAULT ((0))
    );
    PRINT 'Created [change].[DeploymentRegistry]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'change' AND TABLE_NAME = 'PermissionChanges')
BEGIN
    CREATE TABLE [change].[PermissionChanges] (
    [ChangeID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(512) NOT NULL,
    [DatabaseName] nvarchar(512) NULL,
    [PrincipalName] nvarchar(512) NOT NULL,
    [PermissionName] nvarchar(512) NOT NULL,
    [ChangeType] nvarchar(100) NULL,
    [ChangedBy] nvarchar(512) NULL,
    [ChangeTime] datetime NOT NULL,
    [CommandText] nvarchar(MAX) NULL
    );
    PRINT 'Created [change].[PermissionChanges]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'change' AND TABLE_NAME = 'SchemaChanges')
BEGIN
    CREATE TABLE [change].[SchemaChanges] (
    [ChangeID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(512) NOT NULL,
    [DatabaseName] nvarchar(512) NOT NULL,
    [SchemaName] nvarchar(512) NULL,
    [ObjectName] nvarchar(512) NOT NULL,
    [ObjectType] nvarchar(100) NULL,
    [ChangeType] nvarchar(100) NULL,
    [ChangedBy] nvarchar(512) NULL,
    [ChangeTime] datetime NOT NULL,
    [ObjectDefinition] nvarchar(MAX) NULL
    );
    PRINT 'Created [change].[SchemaChanges]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'change' AND TABLE_NAME = 'UnifiedTimeline')
BEGIN
    CREATE TABLE [change].[UnifiedTimeline] (
    [TimelineID] bigint NOT NULL IDENTITY(1,1),
    [ChangeTypeID] int NULL,
    [ServerName] nvarchar(256) NOT NULL,
    [CMSGroupName] nvarchar(400) NULL,
    [CMSCriticality] nvarchar(100) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [ChangeDateTime] datetime2 NOT NULL,
    [ChangeDescription] nvarchar(MAX) NULL,
    [PreviousValue] nvarchar(MAX) NULL,
    [NewValue] nvarchar(MAX) NULL,
    [ChangedBy] nvarchar(200) NULL,
    [SourceSystem] nvarchar(100) NULL,
    [SourceReference] nvarchar(400) NULL,
    [ChangeControlNumber] nvarchar(100) NULL,
    [ImpactLevel] tinyint NULL DEFAULT ((2)),
    [IsPlanned] bit NULL DEFAULT ((0)),
    [RelatedIncidentID] bigint NULL,
    [CollectedDate] datetime2 NULL DEFAULT (getdate())
    );
    PRINT 'Created [change].[UnifiedTimeline]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'compliance' AND TABLE_NAME = 'ArchitectureFindings')
BEGIN
    CREATE TABLE [compliance].[ArchitectureFindings] (
    [FindingID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NULL,
    [FindingType] nvarchar(200) NOT NULL,
    [Severity] nvarchar(40) NOT NULL DEFAULT ('Medium'),
    [Description] nvarchar(MAX) NOT NULL,
    [Impact] nvarchar(MAX) NULL,
    [Recommendation] nvarchar(MAX) NULL,
    [FoundDate] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [Status] nvarchar(40) NOT NULL DEFAULT ('Open')
    );
    PRINT 'Created [compliance].[ArchitectureFindings]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'compliance' AND TABLE_NAME = 'AuditSnapshots')
BEGIN
    CREATE TABLE [compliance].[AuditSnapshots] (
    [SnapshotID] int NOT NULL IDENTITY(1,1),
    [SnapshotName] nvarchar(400) NOT NULL,
    [SnapshotDescription] nvarchar(MAX) NULL,
    [Framework] nvarchar(100) NULL,
    [CMSGroupScope] nvarchar(400) NULL,
    [AuditPeriodStart] date NULL,
    [AuditPeriodEnd] date NULL,
    [CreatedDate] datetime2 NULL DEFAULT (getdate()),
    [CreatedBy] nvarchar(200) NULL DEFAULT (suser_sname()),
    [TotalControls] int NULL DEFAULT ((0)),
    [PassingControls] int NULL DEFAULT ((0)),
    [FailingControls] int NULL DEFAULT ((0)),
    [ExceptionControls] int NULL DEFAULT ((0)),
    [ComplianceScore] decimal(5,2) NULL,
    [Status] nvarchar(100) NULL DEFAULT ('Draft'),
    [ApprovedBy] nvarchar(200) NULL,
    [ApprovedDate] datetime2 NULL,
    [AuditorName] nvarchar(400) NULL
    );
    PRINT 'Created [compliance].[AuditSnapshots]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'compliance' AND TABLE_NAME = 'ComplianceFindings')
BEGIN
    CREATE TABLE [compliance].[ComplianceFindings] (
    [FindingID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [FrameworkName] nvarchar(200) NOT NULL,
    [ControlID] nvarchar(100) NOT NULL,
    [ControlName] nvarchar(400) NOT NULL,
    [Severity] nvarchar(40) NOT NULL DEFAULT ('Medium'),
    [Status] nvarchar(40) NOT NULL DEFAULT ('Open'),
    [AffectedServers] int NULL DEFAULT ((1)),
    [Description] nvarchar(MAX) NULL,
    [Recommendation] nvarchar(MAX) NULL,
    [FoundDate] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [ResolvedDate] datetime2 NULL
    );
    PRINT 'Created [compliance].[ComplianceFindings]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'compliance' AND TABLE_NAME = 'ComplianceFrameworks')
BEGIN
    CREATE TABLE [compliance].[ComplianceFrameworks] (
    [FrameworkID] int NOT NULL IDENTITY(1,1),
    [FrameworkName] nvarchar(200) NOT NULL,
    [FrameworkVersion] nvarchar(100) NULL,
    [Description] nvarchar(1000) NULL,
    [IsActive] bit NOT NULL DEFAULT ((1)),
    [CreatedDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [compliance].[ComplianceFrameworks]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'compliance' AND TABLE_NAME = 'ComplianceScores')
BEGIN
    CREATE TABLE [compliance].[ComplianceScores] (
    [ScoreID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [FrameworkName] nvarchar(200) NOT NULL,
    [OverallScore] decimal(5,2) NULL,
    [TotalControls] int NULL DEFAULT ((0)),
    [PassedControls] int NULL DEFAULT ((0)),
    [FailedControls] int NULL DEFAULT ((0)),
    [AcceptedRisks] int NULL DEFAULT ((0)),
    [LastAssessment] datetime2 NULL,
    [AssessedBy] nvarchar(256) NULL,
    [Notes] nvarchar(MAX) NULL
    );
    PRINT 'Created [compliance].[ComplianceScores]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'compliance' AND TABLE_NAME = 'ControlDefinitions')
BEGIN
    CREATE TABLE [compliance].[ControlDefinitions] (
    [ControlDefID] int NOT NULL IDENTITY(1,1),
    [Framework] nvarchar(100) NOT NULL,
    [ControlID] nvarchar(100) NOT NULL,
    [ControlName] nvarchar(1000) NOT NULL,
    [ControlDescription] nvarchar(MAX) NULL,
    [Category] nvarchar(200) NULL,
    [Severity] nvarchar(100) NULL,
    [EvidenceQuery] nvarchar(MAX) NULL,
    [PassCriteria] nvarchar(1000) NULL,
    [AutoCollect] bit NULL DEFAULT ((0)),
    [CollectionFrequency] nvarchar(100) NULL
    );
    PRINT 'Created [compliance].[ControlDefinitions]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'compliance' AND TABLE_NAME = 'EvidenceStore')
BEGIN
    CREATE TABLE [compliance].[EvidenceStore] (
    [EvidenceID] bigint NOT NULL IDENTITY(1,1),
    [EvidenceGUID] uniqueidentifier NULL DEFAULT (newid()),
    [Framework] nvarchar(100) NOT NULL,
    [ControlID] nvarchar(100) NOT NULL,
    [ControlName] nvarchar(1000) NULL,
    [ServerName] nvarchar(256) NULL,
    [CMSGroupName] nvarchar(400) NULL,
    [CMSCriticality] nvarchar(100) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [CollectionDateTime] datetime2 NULL DEFAULT (getdate()),
    [EvidenceType] nvarchar(100) NULL,
    [EvidenceData] nvarchar(MAX) NULL,
    [EvidenceHash] varbinary NULL,
    [ComplianceStatus] nvarchar(100) NULL,
    [Findings] nvarchar(MAX) NULL,
    [RemediationNotes] nvarchar(MAX) NULL,
    [CollectedBy] nvarchar(200) NULL DEFAULT (suser_sname()),
    [ValidUntil] datetime2 NULL,
    [IsArchived] bit NULL DEFAULT ((0))
    );
    PRINT 'Created [compliance].[EvidenceStore]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'compliance' AND TABLE_NAME = 'Exceptions')
BEGIN
    CREATE TABLE [compliance].[Exceptions] (
    [ExceptionID] int NOT NULL IDENTITY(1,1),
    [Framework] nvarchar(100) NOT NULL,
    [ControlID] nvarchar(100) NOT NULL,
    [ServerName] nvarchar(256) NULL,
    [CMSGroupName] nvarchar(400) NULL,
    [ExceptionReason] nvarchar(MAX) NOT NULL,
    [BusinessJustification] nvarchar(MAX) NULL,
    [MitigatingControls] nvarchar(MAX) NULL,
    [RiskAcceptedBy] nvarchar(200) NULL,
    [RiskAcceptedDate] date NULL,
    [ExpirationDate] date NULL,
    [ReviewDate] date NULL,
    [Status] nvarchar(100) NULL DEFAULT ('Active'),
    [CreatedDate] datetime2 NULL DEFAULT (getdate()),
    [CreatedBy] nvarchar(200) NULL DEFAULT (suser_sname())
    );
    PRINT 'Created [compliance].[Exceptions]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'compliance' AND TABLE_NAME = 'ServerComplianceDetail')
BEGIN
    CREATE TABLE [compliance].[ServerComplianceDetail] (
    [DetailID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [ComplianceTier] nvarchar(200) NULL,
    [CJISScore] decimal(5,2) NULL,
    [NISTScore] decimal(5,2) NULL,
    [STIGScore] decimal(5,2) NULL,
    [DISAScore] decimal(5,2) NULL,
    [OpenFindings] int NULL DEFAULT ((0)),
    [LastAssessment] datetime2 NULL
    );
    PRINT 'Created [compliance].[ServerComplianceDetail]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'ADGroupStandards')
BEGIN
    CREATE TABLE [config].[ADGroupStandards] (
    [ADGroupID] int NOT NULL IDENTITY(1,1),
    [ADGroupName] nvarchar(512) NOT NULL,
    [AccessLevel] varchar(50) NOT NULL,
    [DesiredServerRole] varchar(100) NOT NULL,
    [IsActive] bit NULL DEFAULT ((1)),
    [Notes] nvarchar(MAX) NULL,
    [CreatedDate] datetime2 NULL DEFAULT (sysdatetime()),
    [ModifiedDate] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [config].[ADGroupStandards]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'AlertConfiguration')
BEGIN
    CREATE TABLE [config].[AlertConfiguration] (
    [ConfigId] int NOT NULL IDENTITY(1,1),
    [ConfigKey] varchar(100) NOT NULL,
    [ConfigValue] nvarchar(MAX) NOT NULL,
    [Description] nvarchar(1000) NULL,
    [IsEncrypted] bit NOT NULL DEFAULT ((0)),
    [CreatedAt] datetime2 NOT NULL DEFAULT (getdate()),
    [ModifiedAt] datetime2 NULL,
    [ModifiedBy] nvarchar(256) NULL
    );
    PRINT 'Created [config].[AlertConfiguration]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'AlertControl')
BEGIN
    CREATE TABLE [config].[AlertControl] (
    [IsSilentMode] bit NOT NULL DEFAULT ((0)),
    [ModifiedBy] sysname NOT NULL DEFAULT (suser_sname()),
    [ModifiedOn] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [ControlID] int NOT NULL IDENTITY(1,1)
    );
    PRINT 'Created [config].[AlertControl]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'ApplicationDevOpsMapping')
BEGIN
    CREATE TABLE [config].[ApplicationDevOpsMapping] (
    [MappingID] int NOT NULL IDENTITY(1,1),
    [ApplicationCode] nvarchar(100) NOT NULL,
    [DevOpsProjectName] nvarchar(400) NOT NULL,
    [DevOpsProjectURL] nvarchar(1000) NOT NULL,
    [IsActive] bit NULL DEFAULT ((1)),
    [CreatedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [config].[ApplicationDevOpsMapping]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'ApplicationMapping')
BEGIN
    CREATE TABLE [config].[ApplicationMapping] (
    [MappingID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [ApplicationName] nvarchar(400) NOT NULL,
    [ApplicationCode] nvarchar(40) NOT NULL,
    [ApplicationDescription] nvarchar(1000) NULL,
    [BusinessOwner] nvarchar(200) NULL,
    [TechnicalOwner] nvarchar(200) NULL,
    [SupportGroup] nvarchar(200) NULL,
    [TierLevel] int NOT NULL DEFAULT ((4)),
    [IsPrimaryDatabase] bit NULL DEFAULT ((1)),
    [IsActive] bit NULL DEFAULT ((1)),
    [CreatedDate] datetime2 NULL DEFAULT (getdate()),
    [ModifiedDate] datetime2 NULL DEFAULT (getdate())
    );
    PRINT 'Created [config].[ApplicationMapping]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'BackupComplianceThresholds')
BEGIN
    CREATE TABLE [config].[BackupComplianceThresholds] (
    [ThresholdID] int NOT NULL IDENTITY(1,1),
    [Environment] nvarchar(40) NOT NULL,
    [BackupType] nvarchar(40) NOT NULL,
    [WarningHours] int NULL,
    [CriticalHours] int NULL,
    [ComplianceStandard] nvarchar(200) NULL,
    [Description] nvarchar(1000) NULL
    );
    PRINT 'Created [config].[BackupComplianceThresholds]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'BackupSLA')
BEGIN
    CREATE TABLE [config].[BackupSLA] (
    [SLAID] int NOT NULL IDENTITY(1,1),
    [Environment] nvarchar(100) NOT NULL,
    [BackupType] nvarchar(100) NOT NULL,
    [MaxAgeHours] int NOT NULL,
    [IsEnabled] bit NULL DEFAULT ((1)),
    [CreatedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [config].[BackupSLA]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'BackupSLARules')
BEGIN
    CREATE TABLE [config].[BackupSLARules] (
    [RuleID] int NOT NULL IDENTITY(1,1),
    [EnvironmentType] varchar(20) NOT NULL,
    [BackupType] varchar(20) NOT NULL,
    [MaxAgeHours] int NOT NULL,
    [MaxAgeMinutes] int NULL,
    [RecoveryModelRequired] varchar(20) NULL,
    [Description] varchar(200) NULL,
    [IsActive] bit NULL DEFAULT ((1)),
    [CreatedDate] datetime2 NULL DEFAULT (sysdatetime()),
    [ModifiedDate] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [config].[BackupSLARules]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'CMSGroupPriority')
BEGIN
    CREATE TABLE [config].[CMSGroupPriority] (
    [GroupName] nvarchar(200) NOT NULL,
    [Priority] int NOT NULL,
    [Description] nvarchar(510) NULL
    );
    PRINT 'Created [config].[CMSGroupPriority]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'CMSGroupToTierMapping')
BEGIN
    CREATE TABLE [config].[CMSGroupToTierMapping] (
    [MappingID] int NOT NULL IDENTITY(1,1),
    [CMSGroupName] nvarchar(256) NOT NULL,
    [CMSParentGroupName] nvarchar(256) NULL,
    [ComplianceTier] varchar(100) NOT NULL,
    [TierRationale] nvarchar(1000) NULL,
    [IsActive] bit NULL DEFAULT ((1)),
    [CreatedDate] datetime2 NULL DEFAULT (sysdatetime()),
    [ModifiedDate] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [config].[CMSGroupToTierMapping]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'CollectionStats')
BEGIN
    CREATE TABLE [config].[CollectionStats] (
    [ID] int NOT NULL IDENTITY(1,1),
    [CollectionName] nvarchar(256) NULL,
    [ServerCount] int NULL,
    [RecordCount] int NULL,
    [ErrorCount] int NULL,
    [StartTime] datetime NULL,
    [EndTime] datetime NULL,
    [DurationSeconds] int NULL,
    [Status] nvarchar(40) NULL,
    [LastCollectionTime] datetime NULL,
    [LastCollectionStatus] nvarchar(100) NULL,
    [RecordsCollected] int NULL
    );
    PRINT 'Created [config].[CollectionStats]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'DataRetention')
BEGIN
    CREATE TABLE [config].[DataRetention] (
    [RetentionID] int NOT NULL IDENTITY(1,1),
    [SchemaName] varchar(50) NULL,
    [TableName] varchar(100) NULL,
    [DateColumn] varchar(50) NULL,
    [RetentionDays] int NULL,
    [IsActive] bit NULL DEFAULT ((1)),
    [LastCleanupDate] datetime2 NULL,
    [LastRowsDeleted] int NULL,
    [ArchiveEnabled] bit NULL DEFAULT ((0))
    );
    PRINT 'Created [config].[DataRetention]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'DiskSpaceThresholds')
BEGIN
    CREATE TABLE [config].[DiskSpaceThresholds] (
    [ThresholdID] int NOT NULL IDENTITY(1,1),
    [ThresholdName] nvarchar(100) NOT NULL,
    [UsedPercentMin] int NOT NULL,
    [UsedPercentMax] int NOT NULL,
    [AlertIntervalMinutes] int NOT NULL,
    [Severity] nvarchar(40) NOT NULL,
    [ColorCode] nvarchar(20) NOT NULL,
    [IsEnabled] bit NULL DEFAULT ((1)),
    [CreatedAt] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [config].[DiskSpaceThresholds]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'DocumentationLinks')
BEGIN
    CREATE TABLE [config].[DocumentationLinks] (
    [LinkID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [ApplicationCode] nvarchar(40) NULL,
    [DocumentType] nvarchar(100) NOT NULL,
    [DocumentTitle] nvarchar(400) NOT NULL,
    [DocumentURL] nvarchar(1000) NOT NULL,
    [DocumentDescription] nvarchar(1000) NULL,
    [DisplayOrder] int NULL DEFAULT ((100)),
    [IsActive] bit NULL DEFAULT ((1)),
    [CreatedDate] datetime2 NULL DEFAULT (getdate()),
    [Category] nvarchar(100) NULL DEFAULT ('General'),
    [Icon] nvarchar(20) NULL DEFAULT ('??'),
    [ModifiedDate] datetime NULL DEFAULT (getdate()),
    [CreatedBy] nvarchar(256) NULL DEFAULT (suser_sname()),
    [ModifiedBy] nvarchar(256) NULL DEFAULT (suser_sname())
    );
    PRINT 'Created [config].[DocumentationLinks]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'EmailDistribution')
BEGIN
    CREATE TABLE [config].[EmailDistribution] (
    [DistributionName] sysname NOT NULL,
    [MailProfileName] sysname NULL,
    [ToList] nvarchar(MAX) NOT NULL,
    [CcList] nvarchar(MAX) NULL,
    [IsEnabled] bit NOT NULL DEFAULT ((1)),
    [ModifiedOn] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [config].[EmailDistribution]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'GovernmentCompliance')
BEGIN
    CREATE TABLE [config].[GovernmentCompliance] (
    [ComplianceID] int NOT NULL IDENTITY(1,1),
    [ComplianceName] nvarchar(200) NOT NULL,
    [ComplianceCode] nvarchar(40) NOT NULL,
    [Description] nvarchar(1000) NULL,
    [AppliesTo] nvarchar(200) NULL,
    [AuthorizationLevel] nvarchar(100) NULL,
    [IsActive] bit NULL DEFAULT ((1)),
    [SortOrder] int NULL DEFAULT ((100))
    );
    PRINT 'Created [config].[GovernmentCompliance]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'HealthComplianceThresholds')
BEGIN
    CREATE TABLE [config].[HealthComplianceThresholds] (
    [ThresholdID] int NOT NULL IDENTITY(1,1),
    [MetricName] nvarchar(100) NOT NULL,
    [WarningThreshold] decimal(10,2) NOT NULL,
    [CriticalThreshold] decimal(10,2) NOT NULL,
    [ComparisonType] nvarchar(20) NOT NULL,
    [Standard] nvarchar(100) NOT NULL,
    [Recommendation] nvarchar(1000) NOT NULL,
    [IsEnabled] bit NULL DEFAULT ((1))
    );
    PRINT 'Created [config].[HealthComplianceThresholds]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'LinkedServers')
BEGIN
    CREATE TABLE [config].[LinkedServers] (
    [LinkedServerID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(512) NOT NULL,
    [LinkedServerName] nvarchar(512) NOT NULL,
    [Environment] nvarchar(100) NULL,
    [IsEnabled] bit NULL DEFAULT ((1)),
    [LastVerified] datetime NULL,
    [LastError] nvarchar(MAX) NULL,
    [CreatedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [config].[LinkedServers]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'MaintenanceWindows')
BEGIN
    CREATE TABLE [config].[MaintenanceWindows] (
    [WindowID] int NOT NULL IDENTITY(1,1),
    [WindowName] nvarchar(200) NOT NULL,
    [DayOfWeek] tinyint NULL,
    [StartTime] time NOT NULL,
    [EndTime] time NOT NULL,
    [Environment] nvarchar(100) NULL DEFAULT ('ALL'),
    [IsEnabled] bit NULL DEFAULT ((1)),
    [Description] nvarchar(1000) NULL,
    [WeekOfMonth] int NULL DEFAULT ((0)),
    [DurationMinutes] int NULL DEFAULT ((240)),
    [IsActive] bit NULL DEFAULT ((1)),
    [ComplianceTier] nvarchar(200) NULL,
    [RequiresApproval] bit NULL DEFAULT ((0)),
    [AutoReboot] bit NULL DEFAULT ((0)),
    [AppCategory] nvarchar(200) NULL,
    [NotifyEmail] nvarchar(1000) NULL
    );
    PRINT 'Created [config].[MaintenanceWindows]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'ModernizationPlan')
BEGIN
    CREATE TABLE [config].[ModernizationPlan] (
    [PhaseID] int NOT NULL IDENTITY(1,1),
    [PhaseName] nvarchar(200) NOT NULL,
    [Objective] nvarchar(1000) NOT NULL,
    [Tasks] nvarchar(MAX) NULL,
    [Status] nvarchar(100) NULL DEFAULT ('Planned'),
    [Priority] int NULL,
    [EstimatedEffortDays] int NULL,
    [TargetDate] date NULL,
    [CompletedDate] date NULL,
    [Notes] nvarchar(MAX) NULL
    );
    PRINT 'Created [config].[ModernizationPlan]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'MonitoredInstances')
BEGIN
    CREATE TABLE [config].[MonitoredInstances] (
    [ServerName] nvarchar(510) NOT NULL,
    [InstanceName] nvarchar(510) NULL,
    [TcpPort] int NULL,
    [IsEnabled] bit NOT NULL DEFAULT ((1))
    );
    PRINT 'Created [config].[MonitoredInstances]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'MonitoringThresholds')
BEGIN
    CREATE TABLE [config].[MonitoringThresholds] (
    [ThresholdID] int NOT NULL IDENTITY(1,1),
    [MetricName] nvarchar(200) NOT NULL,
    [WarningThreshold] decimal(18,2) NULL,
    [CriticalThreshold] decimal(18,2) NULL,
    [ComparisonOperator] nvarchar(20) NULL DEFAULT ('>'),
    [Environment] nvarchar(100) NULL DEFAULT ('ALL'),
    [IsEnabled] bit NULL DEFAULT ((1)),
    [CreatedDate] datetime NULL DEFAULT (getdate()),
    [ModifiedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [config].[MonitoringThresholds]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'NonSqlServerClassification')
BEGIN
    CREATE TABLE [config].[NonSqlServerClassification] (
    [ServerName] nvarchar(256) NOT NULL,
    [NonSqlType] nvarchar(100) NOT NULL,
    [AppCategory] nvarchar(200) NULL,
    [LogicalGroupName] nvarchar(256) NULL,
    [Notes] nvarchar(8000) NULL,
    [CreatedDate] datetime2 NOT NULL DEFAULT (sysutcdatetime()),
    [ModifiedDate] datetime2 NULL
    );
    PRINT 'Created [config].[NonSqlServerClassification]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'OnCallRotation')
BEGIN
    CREATE TABLE [config].[OnCallRotation] (
    [RotationId] int NOT NULL IDENTITY(1,1),
    [PrimaryDBA] nvarchar(256) NOT NULL,
    [PrimaryPhone] varchar(20) NOT NULL,
    [PrimaryEmail] nvarchar(512) NULL,
    [BackupDBA] nvarchar(256) NULL,
    [BackupPhone] varchar(20) NULL,
    [BackupEmail] nvarchar(512) NULL,
    [EscalationManager] nvarchar(256) NULL,
    [EscalationPhone] varchar(20) NULL,
    [EscalationEmail] nvarchar(512) NULL,
    [RotationStartDate] date NOT NULL,
    [RotationEndDate] date NOT NULL,
    [Notes] nvarchar(1000) NULL,
    [IsActive] bit NOT NULL DEFAULT ((1)),
    [CreatedAt] datetime2 NOT NULL DEFAULT (getdate()),
    [CreatedBy] nvarchar(256) NOT NULL DEFAULT (suser_sname())
    );
    PRINT 'Created [config].[OnCallRotation]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'ParallelismComplianceStandards')
BEGIN
    CREATE TABLE [config].[ParallelismComplianceStandards] (
    [StandardID] int NOT NULL IDENTITY(1,1),
    [SettingName] nvarchar(100) NOT NULL,
    [MinValue] int NULL,
    [MaxValue] int NULL,
    [RecommendedValue] nvarchar(200) NULL,
    [ComplianceStandard] nvarchar(200) NULL,
    [Rationale] nvarchar(1000) NULL,
    [Recommendation] nvarchar(1000) NULL
    );
    PRINT 'Created [config].[ParallelismComplianceStandards]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'ReachabilityAlertsLog')
BEGIN
    CREATE TABLE [config].[ReachabilityAlertsLog] (
    [AlertID] int NOT NULL IDENTITY(1,1),
    [ServerName] varchar(255) NULL,
    [ErrorMessage] varchar(MAX) NULL,
    [AlertSentOn] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [config].[ReachabilityAlertsLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'ReachabilityStatus')
BEGIN
    CREATE TABLE [config].[ReachabilityStatus] (
    [ServerName] nvarchar(256) NOT NULL,
    [IsOnline] bit NOT NULL,
    [LastChecked] datetime NOT NULL
    );
    PRINT 'Created [config].[ReachabilityStatus]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'RemediationActions')
BEGIN
    CREATE TABLE [config].[RemediationActions] (
    [ActionID] int NOT NULL IDENTITY(1,1),
    [AlertType] nvarchar(100) NOT NULL,
    [ActionName] nvarchar(200) NOT NULL,
    [ActionQuery] nvarchar(MAX) NOT NULL,
    [IsAutoExecute] bit NULL DEFAULT ((0)),
    [Priority] int NULL DEFAULT ((1)),
    [IsEnabled] bit NULL DEFAULT ((1))
    );
    PRINT 'Created [config].[RemediationActions]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'ReplicationPublications')
BEGIN
    CREATE TABLE [config].[ReplicationPublications] (
    [PublicationID] int NOT NULL IDENTITY(1,1),
    [PublisherServer] nvarchar(256) NOT NULL,
    [PublisherDatabase] nvarchar(256) NOT NULL,
    [PublicationName] nvarchar(512) NOT NULL,
    [PublicationType] nvarchar(100) NULL,
    [SubscriberServer] nvarchar(256) NULL,
    [SubscriberDatabase] nvarchar(256) NULL,
    [DistributorServer] nvarchar(256) NULL,
    [ArticleCount] int NULL,
    [IsActive] bit NULL DEFAULT ((1)),
    [IsCritical] bit NULL DEFAULT ((1)),
    [AlertThresholdPendingCmds] int NULL DEFAULT ((10000)),
    [AlertThresholdLatencySeconds] int NULL DEFAULT ((300)),
    [LastInventoryDate] datetime2 NULL DEFAULT (getdate()),
    [CreatedDate] datetime2 NULL DEFAULT (getdate()),
    [LatencyThresholdSeconds] int NULL DEFAULT ((600)),
    [PendingCmdsThreshold] int NULL DEFAULT ((10000))
    );
    PRINT 'Created [config].[ReplicationPublications]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'ReplicationPublishers')
BEGIN
    CREATE TABLE [config].[ReplicationPublishers] (
    [PublisherID] int NOT NULL IDENTITY(1,1),
    [PublisherName] nvarchar(256) NOT NULL,
    [DistributorName] nvarchar(256) NULL,
    [IsActive] bit NOT NULL DEFAULT ((1)),
    [LastChecked] datetime NULL,
    [CreatedDate] datetime NOT NULL DEFAULT (getdate())
    );
    PRINT 'Created [config].[ReplicationPublishers]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'ReplicationServers')
BEGIN
    CREATE TABLE [config].[ReplicationServers] (
    [ReplicationID] int NOT NULL IDENTITY(1,1),
    [PublisherServer] nvarchar(256) NOT NULL,
    [PublisherDatabase] nvarchar(256) NULL,
    [PublicationName] nvarchar(512) NULL,
    [DistributorServer] nvarchar(256) NULL,
    [SubscriberServer] nvarchar(256) NULL,
    [SubscriberDatabase] nvarchar(256) NULL,
    [ReplicationType] nvarchar(100) NULL,
    [ArticleCount] int NULL,
    [IsActive] bit NULL DEFAULT ((1)),
    [IsCritical] bit NULL DEFAULT ((1)),
    [AlertThresholdMinutes] int NULL DEFAULT ((60)),
    [Notes] nvarchar(1000) NULL,
    [CreatedDate] datetime2 NULL DEFAULT (getdate()),
    [LastUpdated] datetime2 NULL DEFAULT (getdate())
    );
    PRINT 'Created [config].[ReplicationServers]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'RepositoryAssignment')
BEGIN
    CREATE TABLE [config].[RepositoryAssignment] (
    [RepositoryID] int NOT NULL IDENTITY(1,1),
    [RepositoryName] varchar(200) NOT NULL,
    [RepoVolume] varchar(10) NOT NULL,
    [RepoTotalTB] decimal(18,2) NULL,
    [RepoFreeTB] decimal(18,2) NULL,
    [RepoFreePercent] decimal(18,2) NULL,
    [IsActive] bit NULL DEFAULT ((1)),
    [LastUpdated] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [config].[RepositoryAssignment]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'ServerComplianceRules')
BEGIN
    CREATE TABLE [config].[ServerComplianceRules] (
    [RuleID] int NOT NULL IDENTITY(1,1),
    [ServerName] varchar(128) NOT NULL,
    [RPOHours] int NOT NULL,
    [BackupMode] varchar(50) NOT NULL,
    [Criticality] varchar(20) NOT NULL,
    [GraceHours] int NULL DEFAULT ((0)),
    [IsActive] bit NULL DEFAULT ((1)),
    [CreatedOn] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [config].[ServerComplianceRules]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'ServerInventory')
BEGIN
    CREATE TABLE [config].[ServerInventory] (
    [ServerID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [InstanceName] nvarchar(256) NULL,
    [Environment] nvarchar(40) NULL,
    [IPAddress] nvarchar(100) NULL,
    [OSVersion] nvarchar(200) NULL,
    [SQLVersion] nvarchar(100) NULL,
    [SQLEdition] nvarchar(100) NULL,
    [CPUCount] int NULL,
    [MaxMemoryMB] int NULL,
    [TotalMemoryMB] int NULL,
    [LastPatchDate] datetime NULL,
    [LastSeen] datetime NULL DEFAULT (getdate()),
    [IsActive] bit NULL DEFAULT ((1)),
    [MaxDOP] int NULL,
    [CostThreshold] int NULL,
    [FQDN] nvarchar(510) NULL,
    [SqlBuild] nvarchar(100) NULL,
    [SqlCumulativeUpdate] nvarchar(100) NULL,
    [WindowsVersion] nvarchar(200) NULL,
    [WindowsBuild] nvarchar(100) NULL,
    [TotalMemoryGB] decimal(10,2) NULL,
    [AppCategory] nvarchar(200) NULL,
    [IsVM] bit NULL,
    [IsClustered] bit NULL,
    [Notes] nvarchar(MAX) NULL,
    [SourceSystem] nvarchar(100) NULL,
    [CreatedDate] datetime2 NULL,
    [HasSSISDB] bit NULL,
    [HasSSRS] bit NULL,
    [ModifiedDate] datetime2 NULL DEFAULT (getdate()),
    [LastInventoryUpdate] datetime2 NULL,
    [ComplianceTier] nvarchar(100) NULL,
    [ComplianceNotes] nvarchar(1000) NULL,
    [DataClassification] nvarchar(200) NULL,
    [CMSServerGroupID] int NULL,
    [CMSGroupName] nvarchar(256) NULL,
    [CMSParentGroupID] int NULL,
    [CMSCriticality] varchar(50) NULL,
    [CMSEnvironment] varchar(50) NULL,
    [CMSLastSyncDate] datetime2 NULL,
    [CMSParentGroupName] nvarchar(256) NULL,
    [ServerType] nvarchar(100) NULL,
    [IsSQLServer] bit NULL DEFAULT ((1))
    );
    PRINT 'Created [config].[ServerInventory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'ServerNameMap')
BEGIN
    CREATE TABLE [config].[ServerNameMap] (
    [InventoryServerKey] nvarchar(512) NOT NULL,
    [StatusServerKey] nvarchar(512) NOT NULL,
    [IsActive] bit NOT NULL DEFAULT ((1)),
    [Notes] nvarchar(1000) NULL,
    [ModifiedBy] sysname NOT NULL DEFAULT (suser_sname()),
    [ModifiedOn] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [config].[ServerNameMap]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'ServerReachability')
BEGIN
    CREATE TABLE [config].[ServerReachability] (
    [CheckID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(510) NULL,
    [Reachable] bit NULL,
    [ErrorMessage] nvarchar(8000) NULL,
    [CheckedOn] datetime NULL DEFAULT (getdate()),
    [TcpPort] int NULL
    );
    PRINT 'Created [config].[ServerReachability]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'ServerRoleMapping')
BEGIN
    CREATE TABLE [config].[ServerRoleMapping] (
    [ServerRoleMappingID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [ServerRole] nvarchar(256) NOT NULL,
    [IsPrimaryRole] bit NOT NULL DEFAULT ((0)),
    [Environment] nvarchar(100) NULL,
    [Notes] nvarchar(510) NULL,
    [CreatedDate] datetime2 NULL DEFAULT (getdate()),
    [CreatedBy] nvarchar(256) NULL DEFAULT (suser_sname()),
    [ModifiedDate] datetime2 NULL DEFAULT (getdate()),
    [ModifiedBy] nvarchar(256) NULL DEFAULT (suser_sname()),
    [IsActive] bit NULL DEFAULT ((1))
    );
    PRINT 'Created [config].[ServerRoleMapping]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'ServerThresholdOverrides')
BEGIN
    CREATE TABLE [config].[ServerThresholdOverrides] (
    [OverrideID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DriveLetter] nvarchar(20) NULL,
    [MetricName] nvarchar(200) NOT NULL,
    [WarningThreshold] decimal(10,2) NULL,
    [CriticalThreshold] decimal(10,2) NULL,
    [Reason] nvarchar(1000) NULL,
    [IsEnabled] bit NULL DEFAULT ((1)),
    [CreatedDate] datetime NULL DEFAULT (getdate()),
    [CreatedBy] nvarchar(256) NULL DEFAULT (suser_sname()),
    [ModifiedDate] datetime NULL
    );
    PRINT 'Created [config].[ServerThresholdOverrides]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'SqlInstanceOverrides')
BEGIN
    CREATE TABLE [config].[SqlInstanceOverrides] (
    [ServerName] nvarchar(256) NOT NULL,
    [InstanceName] nvarchar(256) NOT NULL,
    [Notes] nvarchar(4000) NULL,
    [CreatedDate] datetime2 NOT NULL DEFAULT (sysutcdatetime()),
    [ModifiedDate] datetime2 NULL
    );
    PRINT 'Created [config].[SqlInstanceOverrides]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'SqlServicingTargets')
BEGIN
    CREATE TABLE [config].[SqlServicingTargets] (
    [SqlYear] int NOT NULL,
    [TargetCUNumber] int NULL,
    [TargetBuild] nvarchar(100) NULL,
    [TargetKB] nvarchar(40) NULL,
    [ReleaseDate] date NULL,
    [Notes] nvarchar(400) NULL
    );
    PRINT 'Created [config].[SqlServicingTargets]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'SqlSupportLifecycle')
BEGIN
    CREATE TABLE [config].[SqlSupportLifecycle] (
    [SqlYear] int NOT NULL,
    [ExtendedSupportEnd] date NOT NULL,
    [Notes] nvarchar(400) NULL
    );
    PRINT 'Created [config].[SqlSupportLifecycle]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'TargetServers')
BEGIN
    CREATE TABLE [config].[TargetServers] (
    [ServerID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(510) NOT NULL,
    [IsEnabled] bit NOT NULL DEFAULT ((1)),
    [LastContact] datetime NULL,
    [LastStatus] nvarchar(100) NULL
    );
    PRINT 'Created [config].[TargetServers]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'VeeamJobGroupMapping')
BEGIN
    CREATE TABLE [config].[VeeamJobGroupMapping] (
    [MappingID] int NOT NULL IDENTITY(1,1),
    [VeeamJobGroup] nvarchar(200) NOT NULL,
    [RepositoryName] nvarchar(200) NOT NULL,
    [RepoVolume] nvarchar(20) NULL,
    [IsActive] bit NULL DEFAULT ((1)),
    [CreatedDate] datetime2 NULL DEFAULT (getdate())
    );
    PRINT 'Created [config].[VeeamJobGroupMapping]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'VeeamObjectMap')
BEGIN
    CREATE TABLE [config].[VeeamObjectMap] (
    [MapID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [VmName] nvarchar(256) NULL,
    [VeeamObjectID] nvarchar(400) NULL,
    [VeeamJobName] nvarchar(400) NULL,
    [Repository] nvarchar(400) NULL,
    [AddedOn] datetime NULL DEFAULT (getdate()),
    [IsActive] bit NULL DEFAULT ((1))
    );
    PRINT 'Created [config].[VeeamObjectMap]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'config' AND TABLE_NAME = 'WindowsUpdateCompliance')
BEGIN
    CREATE TABLE [config].[WindowsUpdateCompliance] (
    [ServerName] nvarchar(256) NOT NULL,
    [AllowMUUpdateService] int NULL,
    [ComplianceStatus] varchar(13) NOT NULL,
    [LastChecked] datetime NULL DEFAULT (getdate()),
    [LastEnforced] datetime NULL,
    [Notes] nvarchar(1000) NULL
    );
    PRINT 'Created [config].[WindowsUpdateCompliance]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'control' AND TABLE_NAME = 'AlertThresholds')
BEGIN
    CREATE TABLE [control].[AlertThresholds] (
    [ThresholdID] int NOT NULL IDENTITY(1,1),
    [MetricName] nvarchar(100) NOT NULL,
    [WarningThreshold] decimal(18,2) NULL,
    [CriticalThreshold] decimal(18,2) NULL,
    [IsEnabled] bit NULL DEFAULT ((1)),
    [CooldownMinutes] int NULL DEFAULT ((30)),
    [CreatedDate] datetime2 NULL DEFAULT (getdate())
    );
    PRINT 'Created [control].[AlertThresholds]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'control' AND TABLE_NAME = 'ExternalProcessConfig')
BEGIN
    CREATE TABLE [control].[ExternalProcessConfig] (
    [ConfigID] int NOT NULL IDENTITY(1,1),
    [ServerKey] int NOT NULL,
    [Server] varchar(100) NOT NULL,
    [ProcessName] varchar(128) NOT NULL,
    [ProcessDisplayName] varchar(128) NULL,
    [ThrottleEnabled] bit NULL DEFAULT ((1)),
    [NormalPriority] varchar(20) NULL DEFAULT ('Normal'),
    [ThrottledPriority] varchar(20) NULL DEFAULT ('BelowNormal'),
    [NormalCPUAffinity] bigint NULL,
    [ThrottledCPUAffinity] bigint NULL,
    [ThrottleWhenSQLCPUAbove] decimal(5,2) NULL DEFAULT ((70.00)),
    [RestoreWhenSQLCPUBelow] decimal(5,2) NULL DEFAULT ((40.00)),
    [EvaluationWindowMinutes] int NULL DEFAULT ((10)),
    [CurrentState] varchar(20) NULL DEFAULT ('Normal'),
    [LastStateChange] datetime2 NULL,
    [LastEvaluationTime] datetime2 NULL,
    [ConsecutiveThrottleCount] int NULL DEFAULT ((0)),
    [CreatedDate] datetime2 NULL DEFAULT (getdate()),
    [ModifiedDate] datetime2 NULL DEFAULT (getdate()),
    [ModifiedBy] varchar(128) NULL DEFAULT (suser_sname()),
    [Notes] varchar(500) NULL
    );
    PRINT 'Created [control].[ExternalProcessConfig]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'correlation' AND TABLE_NAME = 'AlertQueue')
BEGIN
    CREATE TABLE [correlation].[AlertQueue] (
    [AlertQueueID] bigint NOT NULL IDENTITY(1,1),
    [AlertType] varchar(100) NOT NULL,
    [Severity] tinyint NOT NULL DEFAULT ((3)),
    [SourceServer] varchar(256) NULL,
    [SourceDatabase] varchar(256) NULL,
    [AlertMessage] nvarchar(MAX) NULL,
    [AlertData] nvarchar(MAX) NULL,
    [ReceivedDate] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [ProcessedDate] datetime2 NULL,
    [IsProcessed] bit NOT NULL DEFAULT ((0)),
    [FingerprintHash] varchar(64) NULL,
    [IncidentID] int NULL
    );
    PRINT 'Created [correlation].[AlertQueue]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'correlation' AND TABLE_NAME = 'CorrelationRules')
BEGIN
    CREATE TABLE [correlation].[CorrelationRules] (
    [RuleID] int NOT NULL IDENTITY(1,1),
    [RuleName] nvarchar(200) NOT NULL,
    [RuleDescription] nvarchar(1000) NULL,
    [AlertTypePattern] nvarchar(400) NULL,
    [CMSGroupPattern] nvarchar(400) NULL,
    [TimeWindowMinutes] int NULL DEFAULT ((15)),
    [MinAlertCount] int NULL DEFAULT ((2)),
    [Priority] int NULL DEFAULT ((100)),
    [IsEnabled] bit NULL DEFAULT ((1)),
    [CreatedDate] datetime2 NULL DEFAULT (getdate()),
    [ModifiedDate] datetime2 NULL DEFAULT (getdate())
    );
    PRINT 'Created [correlation].[CorrelationRules]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'correlation' AND TABLE_NAME = 'EscalationPaths')
BEGIN
    CREATE TABLE [correlation].[EscalationPaths] (
    [EscalationPathID] int NOT NULL IDENTITY(1,1),
    [CMSGroupPattern] nvarchar(400) NOT NULL,
    [Severity] tinyint NOT NULL,
    [EscalationLevel] int NULL DEFAULT ((1)),
    [EscalationMinutes] int NULL DEFAULT ((15)),
    [NotificationChannel] nvarchar(100) NULL,
    [NotificationTarget] nvarchar(1000) NULL,
    [IsEnabled] bit NULL DEFAULT ((1))
    );
    PRINT 'Created [correlation].[EscalationPaths]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'correlation' AND TABLE_NAME = 'Fingerprints')
BEGIN
    CREATE TABLE [correlation].[Fingerprints] (
    [FingerprintID] bigint NOT NULL IDENTITY(1,1),
    [FingerprintHash] varbinary NOT NULL,
    [AlertType] nvarchar(200) NOT NULL,
    [ServerName] nvarchar(256) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [MetricName] nvarchar(200) NULL,
    [ThresholdValue] decimal(18,4) NULL,
    [FirstSeenDate] datetime2 NULL DEFAULT (getdate()),
    [LastSeenDate] datetime2 NULL DEFAULT (getdate()),
    [OccurrenceCount] int NULL DEFAULT ((1)),
    [SuppressionWindowMinutes] int NULL DEFAULT ((10)),
    [IsActive] bit NULL DEFAULT ((1))
    );
    PRINT 'Created [correlation].[Fingerprints]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'correlation' AND TABLE_NAME = 'IncidentAlerts')
BEGIN
    CREATE TABLE [correlation].[IncidentAlerts] (
    [IncidentAlertID] bigint NOT NULL IDENTITY(1,1),
    [IncidentID] bigint NOT NULL,
    [AlertID] bigint NOT NULL,
    [FingerprintID] bigint NULL,
    [AlertDateTime] datetime2 NOT NULL,
    [AlertType] nvarchar(200) NULL,
    [ServerName] nvarchar(256) NULL,
    [IsRootCause] bit NULL DEFAULT ((0))
    );
    PRINT 'Created [correlation].[IncidentAlerts]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'correlation' AND TABLE_NAME = 'Incidents')
BEGIN
    CREATE TABLE [correlation].[Incidents] (
    [IncidentID] bigint NOT NULL IDENTITY(1,1),
    [IncidentNumber] varchar(9) NULL,
    [Title] nvarchar(1000) NOT NULL,
    [Description] nvarchar(MAX) NULL,
    [Severity] tinyint NOT NULL DEFAULT ((3)),
    [Status] nvarchar(100) NULL DEFAULT ('Open'),
    [PrimaryServerName] nvarchar(256) NULL,
    [AffectedServers] nvarchar(MAX) NULL,
    [CMSGroupName] nvarchar(400) NULL,
    [Environment] nvarchar(100) NULL,
    [AlertCount] int NULL DEFAULT ((0)),
    [CorrelationRuleID] int NULL,
    [RootCauseAlertID] bigint NULL,
    [CreatedDate] datetime2 NULL DEFAULT (getdate()),
    [AcknowledgedDate] datetime2 NULL,
    [AcknowledgedBy] nvarchar(200) NULL,
    [ResolvedDate] datetime2 NULL,
    [ResolvedBy] nvarchar(200) NULL,
    [ResolutionNotes] nvarchar(MAX) NULL,
    [PlaybookID] int NULL,
    [TrackITTicket] nvarchar(100) NULL,
    [MTTR_Minutes] int NULL
    );
    PRINT 'Created [correlation].[Incidents]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'correlation' AND TABLE_NAME = 'SuppressionRules')
BEGIN
    CREATE TABLE [correlation].[SuppressionRules] (
    [SuppressionID] int NOT NULL IDENTITY(1,1),
    [RuleName] nvarchar(200) NOT NULL,
    [AlertTypePattern] nvarchar(400) NULL,
    [ServerPattern] nvarchar(400) NULL,
    [CMSGroupPattern] nvarchar(400) NULL,
    [StartTime] datetime2 NULL,
    [EndTime] datetime2 NULL,
    [Reason] nvarchar(1000) NULL,
    [ChangeControlNumber] nvarchar(100) NULL,
    [CreatedBy] nvarchar(200) NULL,
    [CreatedDate] datetime2 NULL DEFAULT (getdate()),
    [IsEnabled] bit NULL DEFAULT ((1))
    );
    PRINT 'Created [correlation].[SuppressionRules]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Credentials' AND TABLE_NAME = 'CredentialAccessLog')
BEGIN
    CREATE TABLE [Credentials].[CredentialAccessLog] (
    [AccessLogID] bigint NOT NULL IDENTITY(1,1),
    [CredentialID] int NOT NULL,
    [AccessDateTime] datetime2 NULL DEFAULT (getdate()),
    [AccessedBy] nvarchar(510) NOT NULL,
    [AccessMethod] nvarchar(200) NULL,
    [SourceHost] nvarchar(510) NULL,
    [AccessResult] nvarchar(100) NULL
    );
    PRINT 'Created [Credentials].[CredentialAccessLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Credentials' AND TABLE_NAME = 'CredentialInventory')
BEGIN
    CREATE TABLE [Credentials].[CredentialInventory] (
    [CredentialID] int NOT NULL IDENTITY(1,1),
    [CredentialName] nvarchar(510) NOT NULL,
    [CredentialDescription] nvarchar(2000) NULL,
    [Username] nvarchar(510) NULL,
    [Domain] nvarchar(200) NULL,
    [CredentialTypeID] int NOT NULL,
    [VaultTypeID] int NOT NULL,
    [SensitivityID] int NOT NULL,
    [MigrationStatusID] int NOT NULL,
    [SourceSystem] nvarchar(200) NULL DEFAULT ('KeePass'),
    [SourceServer] nvarchar(510) NULL DEFAULT ('AZSQLADMIN19'),
    [KeePassGroup] nvarchar(1000) NULL,
    [KeePassEntryUUID] nvarchar(200) NULL,
    [VaultPath] nvarchar(1000) NULL,
    [VaultSecretName] nvarchar(510) NULL,
    [TargetServerName] nvarchar(510) NULL,
    [ApplicationName] nvarchar(510) NULL,
    [CreatedDate] datetime2 NULL DEFAULT (getdate()),
    [CreatedBy] nvarchar(510) NULL DEFAULT (suser_sname()),
    [LastModifiedDate] datetime2 NULL,
    [LastModifiedBy] nvarchar(510) NULL,
    [LastRotatedDate] datetime2 NULL,
    [NextRotationDate] datetime2 NULL,
    [RotationFrequencyDays] int NULL DEFAULT ((90)),
    [OwnerTeam] nvarchar(510) NULL,
    [OwnerEmail] nvarchar(510) NULL,
    [STIGCompliant] bit NULL DEFAULT ((0)),
    [CJISRelevant] bit NULL DEFAULT ((0)),
    [LastComplianceCheckDate] datetime2 NULL,
    [MigrationDate] datetime2 NULL,
    [MigrationNotes] nvarchar(MAX) NULL,
    [IsActive] bit NULL DEFAULT ((1)),
    [Notes] nvarchar(MAX) NULL
    );
    PRINT 'Created [Credentials].[CredentialInventory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Credentials' AND TABLE_NAME = 'CredentialType')
BEGIN
    CREATE TABLE [Credentials].[CredentialType] (
    [CredentialTypeID] int NOT NULL IDENTITY(1,1),
    [TypeName] nvarchar(100) NOT NULL,
    [TypeDescription] nvarchar(1000) NULL,
    [IsActive] bit NULL DEFAULT ((1))
    );
    PRINT 'Created [Credentials].[CredentialType]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Credentials' AND TABLE_NAME = 'DataSensitivity')
BEGIN
    CREATE TABLE [Credentials].[DataSensitivity] (
    [SensitivityID] int NOT NULL IDENTITY(1,1),
    [SensitivityLevel] nvarchar(100) NOT NULL,
    [RotationFrequencyDays] int NULL,
    [RequiresMFA] bit NULL DEFAULT ((0)),
    [RequiresApproval] bit NULL DEFAULT ((0))
    );
    PRINT 'Created [Credentials].[DataSensitivity]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Credentials' AND TABLE_NAME = 'KeePassCurrentSnapshot')
BEGIN
    CREATE TABLE [Credentials].[KeePassCurrentSnapshot] (
    [SnapshotID] int NOT NULL IDENTITY(1,1),
    [KeePassTitle] nvarchar(1000) NULL,
    [KeePassUsername] nvarchar(510) NULL,
    [KeePassURL] nvarchar(2000) NULL,
    [KeePassNotes] nvarchar(MAX) NULL,
    [ContentHash] varbinary NULL,
    [LastSeenDateTime] datetime2 NULL DEFAULT (getdate()),
    [FirstSeenDateTime] datetime2 NULL DEFAULT (getdate()),
    [LinkedCredentialID] int NULL,
    [IsActive] bit NULL DEFAULT ((1))
    );
    PRINT 'Created [Credentials].[KeePassCurrentSnapshot]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Credentials' AND TABLE_NAME = 'KeePassMigrationStaging')
BEGIN
    CREATE TABLE [Credentials].[KeePassMigrationStaging] (
    [StagingID] int NOT NULL IDENTITY(1,1),
    [KeePassGroup] nvarchar(1000) NULL,
    [KeePassTitle] nvarchar(1000) NULL,
    [KeePassUsername] nvarchar(510) NULL,
    [KeePassURL] nvarchar(2000) NULL,
    [KeePassNotes] nvarchar(MAX) NULL,
    [KeePassUUID] nvarchar(200) NULL,
    [AssignedCredentialType] nvarchar(100) NULL,
    [AssignedSensitivity] nvarchar(100) NULL,
    [AssignedVaultType] nvarchar(100) NULL,
    [ProcessingStatus] nvarchar(100) NULL DEFAULT ('Pending'),
    [ProcessingNotes] nvarchar(MAX) NULL,
    [ProcessedDate] datetime2 NULL,
    [ProcessedBy] nvarchar(510) NULL,
    [MigratedCredentialID] int NULL,
    [ImportedDate] datetime2 NULL DEFAULT (getdate()),
    [ImportedBy] nvarchar(510) NULL DEFAULT (suser_sname())
    );
    PRINT 'Created [Credentials].[KeePassMigrationStaging]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Credentials' AND TABLE_NAME = 'KeePassSyncHistory')
BEGIN
    CREATE TABLE [Credentials].[KeePassSyncHistory] (
    [SyncID] bigint NOT NULL IDENTITY(1,1),
    [SyncDateTime] datetime2 NULL DEFAULT (getdate()),
    [SyncType] nvarchar(100) NULL,
    [TotalEntriesInSource] int NULL,
    [NewEntriesFound] int NULL,
    [ModifiedEntriesFound] int NULL,
    [DeletedEntriesFound] int NULL,
    [EntriesProcessed] int NULL,
    [ErrorsEncountered] int NULL,
    [SyncStatus] nvarchar(100) NULL,
    [ErrorMessage] nvarchar(MAX) NULL,
    [StartTime] datetime2 NULL,
    [EndTime] datetime2 NULL,
    [DurationSeconds] int NULL,
    [ExecutedBy] nvarchar(510) NULL DEFAULT (suser_sname())
    );
    PRINT 'Created [Credentials].[KeePassSyncHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Credentials' AND TABLE_NAME = 'KeePassSyncQueue')
BEGIN
    CREATE TABLE [Credentials].[KeePassSyncQueue] (
    [QueueID] bigint NOT NULL IDENTITY(1,1),
    [KeePassTitle] nvarchar(1000) NULL,
    [KeePassUsername] nvarchar(510) NULL,
    [KeePassURL] nvarchar(2000) NULL,
    [KeePassNotes] nvarchar(MAX) NULL,
    [ChangeType] nvarchar(100) NULL,
    [DetectedDateTime] datetime2 NULL DEFAULT (getdate()),
    [ExistingCredentialID] int NULL,
    [ProcessingStatus] nvarchar(100) NULL DEFAULT ('Pending'),
    [ProcessedDateTime] datetime2 NULL,
    [ProcessedBy] nvarchar(510) NULL,
    [ProcessingNotes] nvarchar(MAX) NULL,
    [RequiresApproval] bit NULL DEFAULT ((0))
    );
    PRINT 'Created [Credentials].[KeePassSyncQueue]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Credentials' AND TABLE_NAME = 'KeePassSyncStaging')
BEGIN
    CREATE TABLE [Credentials].[KeePassSyncStaging] (
    [ID] int NOT NULL IDENTITY(1,1),
    [KeePassTitle] nvarchar(1000) NULL,
    [KeePassUsername] nvarchar(510) NULL,
    [KeePassURL] nvarchar(2000) NULL,
    [KeePassNotes] nvarchar(MAX) NULL,
    [ImportedAt] datetime2 NULL DEFAULT (getdate())
    );
    PRINT 'Created [Credentials].[KeePassSyncStaging]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Credentials' AND TABLE_NAME = 'MigrationStatus')
BEGIN
    CREATE TABLE [Credentials].[MigrationStatus] (
    [StatusID] int NOT NULL IDENTITY(1,1),
    [StatusName] nvarchar(100) NOT NULL,
    [StatusDescription] nvarchar(1000) NULL
    );
    PRINT 'Created [Credentials].[MigrationStatus]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Credentials' AND TABLE_NAME = 'VaultType')
BEGIN
    CREATE TABLE [Credentials].[VaultType] (
    [VaultTypeID] int NOT NULL IDENTITY(1,1),
    [VaultName] nvarchar(200) NOT NULL,
    [VaultDescription] nvarchar(1000) NULL,
    [IsActive] bit NULL DEFAULT ((1))
    );
    PRINT 'Created [Credentials].[VaultType]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ctl' AND TABLE_NAME = 'BackupCompliance')
BEGIN
    CREATE TABLE [ctl].[BackupCompliance] (
    [ComplianceID] int NOT NULL IDENTITY(1,1),
    [BackupSource] varchar(20) NOT NULL,
    [ServerName] varchar(128) NOT NULL,
    [VmName] varchar(128) NULL,
    [DatabaseName] varchar(256) NULL,
    [BackupType] varchar(50) NULL,
    [LastBackupTime] datetime NULL,
    [NextExpectedBackupTime] datetime NULL,
    [CollectionTime] datetime NULL DEFAULT (getdate()),
    [JobName] varchar(256) NULL,
    [Status] varchar(50) NULL,
    [BackupMode] varchar(50) NULL,
    [BackupSizeGB] decimal(18,2) NULL,
    [Repository] varchar(128) NULL,
    [RepositoryVolume] varchar(5) NULL,
    [RepoTotalTB] decimal(18,2) NULL,
    [RepoFreeTB] decimal(18,2) NULL,
    [RepoFreePercent] decimal(38,16) NULL,
    [IsCompliant] bit NOT NULL DEFAULT ((0)),
    [RPOHours] int NULL,
    [LastFullBackupTime] datetime2 NULL,
    [LastLogBackupTime] datetime2 NULL,
    [FullAgeHours] int NULL,
    [LogAgeMinutes] int NULL,
    [ComplianceScore] decimal(5,2) NULL,
    [AnomalyScore] decimal(10,6) NULL,
    [ForecastFailureHours] decimal(18,2) NULL,
    [ExpectedFrequency] varchar(50) NULL,
    [LoadDate] datetime NOT NULL DEFAULT (getdate()),
    [AgeMinutes] int NULL
    );
    PRINT 'Created [ctl].[BackupCompliance]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ctl' AND TABLE_NAME = 'DataSources')
BEGIN
    CREATE TABLE [ctl].[DataSources] (
    [SourceID] int NOT NULL IDENTITY(1,1),
    [SourceName] nvarchar(512) NOT NULL,
    [SourceType] nvarchar(100) NULL,
    [ConnectionString] nvarchar(2000) NULL,
    [IsEnabled] bit NULL DEFAULT ((1)),
    [LastTestedDate] datetime NULL,
    [LastTestResult] nvarchar(100) NULL
    );
    PRINT 'Created [ctl].[DataSources]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ctl' AND TABLE_NAME = 'ETLErrorLog')
BEGIN
    CREATE TABLE [ctl].[ETLErrorLog] (
    [ErrorID] int NOT NULL IDENTITY(1,1),
    [ProcedureName] varchar(200) NULL,
    [ErrorMessage] varchar(MAX) NULL,
    [ErrorLine] int NULL,
    [LogDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [ctl].[ETLErrorLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ctl' AND TABLE_NAME = 'ETLExecutionLog')
BEGIN
    CREATE TABLE [ctl].[ETLExecutionLog] (
    [ExecutionID] bigint NOT NULL IDENTITY(1,1),
    [PackageID] int NULL,
    [PackageName] nvarchar(512) NOT NULL,
    [StartTime] datetime NOT NULL,
    [EndTime] datetime NULL,
    [Status] nvarchar(100) NULL,
    [RowsProcessed] bigint NULL,
    [RowsInserted] bigint NULL,
    [RowsUpdated] bigint NULL,
    [RowsDeleted] bigint NULL,
    [ErrorMessage] nvarchar(MAX) NULL
    );
    PRINT 'Created [ctl].[ETLExecutionLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ctl' AND TABLE_NAME = 'ETLPackages')
BEGIN
    CREATE TABLE [ctl].[ETLPackages] (
    [PackageID] int NOT NULL IDENTITY(1,1),
    [PackageName] nvarchar(512) NOT NULL,
    [PackageDescription] nvarchar(1000) NULL,
    [SourceType] nvarchar(100) NULL,
    [SourceConnection] nvarchar(1000) NULL,
    [TargetSchema] nvarchar(256) NULL,
    [TargetTable] nvarchar(512) NULL,
    [ScheduleFrequency] nvarchar(100) NULL,
    [IsEnabled] bit NULL DEFAULT ((1)),
    [LastExecutionTime] datetime NULL,
    [LastExecutionStatus] nvarchar(100) NULL,
    [CreatedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [ctl].[ETLPackages]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ctl' AND TABLE_NAME = 'FrameworkAlertRules')
BEGIN
    CREATE TABLE [ctl].[FrameworkAlertRules] (
    [AlertID] int NOT NULL IDENTITY(1,1),
    [RuleName] varchar(200) NULL,
    [Severity] varchar(20) NULL,
    [ThresholdValue] varchar(100) NULL,
    [NotificationGroup] varchar(200) NULL
    );
    PRINT 'Created [ctl].[FrameworkAlertRules]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ctl' AND TABLE_NAME = 'FrameworkJobs')
BEGIN
    CREATE TABLE [ctl].[FrameworkJobs] (
    [JobID] int NOT NULL IDENTITY(1,1),
    [JobName] varchar(200) NULL,
    [ScriptPath] varchar(400) NULL,
    [Enabled] bit NULL DEFAULT ((1)),
    [ScheduleDescription] varchar(200) NULL
    );
    PRINT 'Created [ctl].[FrameworkJobs]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ctl' AND TABLE_NAME = 'FrameworkSettings')
BEGIN
    CREATE TABLE [ctl].[FrameworkSettings] (
    [SettingName] varchar(100) NOT NULL,
    [SettingValue] varchar(500) NULL,
    [LastModified] datetime2 NULL DEFAULT (sysutcdatetime())
    );
    PRINT 'Created [ctl].[FrameworkSettings]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ctl' AND TABLE_NAME = 'JobCompliance')
BEGIN
    CREATE TABLE [ctl].[JobCompliance] (
    [ComplianceID] int NOT NULL IDENTITY(1,1),
    [ServerName] sysname NOT NULL,
    [JobName] sysname NOT NULL,
    [LastRunDateTime] datetime NULL,
    [LastRunStatus] varchar(20) NOT NULL,
    [ExpectedFrequency] varchar(50) NULL,
    [IsCompliant] bit NOT NULL,
    [CollectionTime] datetime NOT NULL DEFAULT (getdate())
    );
    PRINT 'Created [ctl].[JobCompliance]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ctl' AND TABLE_NAME = 'JobHistory')
BEGIN
    CREATE TABLE [ctl].[JobHistory] (
    [JobName] nvarchar(510) NULL,
    [RunDate] datetime NULL,
    [RunStatus] nvarchar(100) NULL,
    [Duration] nvarchar(100) NULL,
    [StepName] nvarchar(510) NULL,
    [Message] nvarchar(MAX) NULL,
    [DurationSeconds] int NULL,
    [CollectedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [ctl].[JobHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ctl' AND TABLE_NAME = 'JobHistoryCSV_Stage')
BEGIN
    CREATE TABLE [ctl].[JobHistoryCSV_Stage] (
    [JobName] nvarchar(510) NULL,
    [run_date] nvarchar(100) NULL,
    [run_time] nvarchar(100) NULL,
    [run_duration] nvarchar(100) NULL,
    [run_status] nvarchar(100) NULL
    );
    PRINT 'Created [ctl].[JobHistoryCSV_Stage]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ctl' AND TABLE_NAME = 'LoginCompliance')
BEGIN
    CREATE TABLE [ctl].[LoginCompliance] (
    [ComplianceID] int NOT NULL IDENTITY(1,1),
    [ServerName] sysname NOT NULL,
    [LoginName] sysname NOT NULL,
    [Status] varchar(20) NOT NULL,
    [MustChange] bit NULL,
    [IsDisabled] bit NULL,
    [CollectionTime] datetime NOT NULL DEFAULT (getdate())
    );
    PRINT 'Created [ctl].[LoginCompliance]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ctl' AND TABLE_NAME = 'ReplicationErrors')
BEGIN
    CREATE TABLE [ctl].[ReplicationErrors] (
    [ErrorID] int NOT NULL IDENTITY(1,1),
    [PublisherServer] nvarchar(256) NOT NULL,
    [ErrorDate] datetime2 NULL,
    [ProcessInfo] nvarchar(100) NULL,
    [ErrorMessage] nvarchar(4000) NULL,
    [Severity] nvarchar(40) NULL,
    [CollectionTime] datetime2 NULL DEFAULT (getdate())
    );
    PRINT 'Created [ctl].[ReplicationErrors]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ctl' AND TABLE_NAME = 'ReplicationHealth')
BEGIN
    CREATE TABLE [ctl].[ReplicationHealth] (
    [HealthID] int NOT NULL IDENTITY(1,1),
    [ReplicationID] int NULL,
    [PublisherServer] nvarchar(256) NOT NULL,
    [PublisherDatabase] nvarchar(256) NULL,
    [SubscriberServer] nvarchar(256) NULL,
    [SubscriberDatabase] nvarchar(256) NULL,
    [PublicationName] nvarchar(512) NULL,
    [LatencySeconds] int NULL,
    [PendingCommands] bigint NULL,
    [LastSyncTime] datetime2 NULL,
    [Status] nvarchar(100) NULL,
    [StatusMessage] nvarchar(1000) NULL,
    [CollectionTime] datetime2 NULL DEFAULT (getdate()),
    [IsHealthy] bit NULL DEFAULT ((1))
    );
    PRINT 'Created [ctl].[ReplicationHealth]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ctl' AND TABLE_NAME = 'ReplicationMetrics')
BEGIN
    CREATE TABLE [ctl].[ReplicationMetrics] (
    [MetricID] int NOT NULL IDENTITY(1,1),
    [PublisherServer] nvarchar(256) NOT NULL,
    [PublisherDatabase] nvarchar(256) NULL,
    [PublicationName] nvarchar(512) NULL,
    [SubscriberServer] nvarchar(256) NULL,
    [SubscriberDatabase] nvarchar(256) NULL,
    [PendingCmdCount] bigint NULL,
    [EstimatedProcessTime] int NULL,
    [LatencySeconds] int NULL,
    [DeliveryRate] float NULL,
    [AgentStatus] nvarchar(100) NULL,
    [LastSyncTime] datetime2 NULL,
    [Status] nvarchar(100) NULL,
    [StatusMessage] nvarchar(1000) NULL,
    [CollectionTime] datetime2 NULL DEFAULT (getdate()),
    [PendingCmds] int NULL
    );
    PRINT 'Created [ctl].[ReplicationMetrics]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ctl' AND TABLE_NAME = 'RepositoryStatus')
BEGIN
    CREATE TABLE [ctl].[RepositoryStatus] (
    [StatusID] int NOT NULL IDENTITY(1,1),
    [MetricName] nvarchar(256) NULL,
    [MetricValue] nvarchar(512) NULL,
    [CollectedAt] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [ctl].[RepositoryStatus]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ctl' AND TABLE_NAME = 'ServerInventoryHistory')
BEGIN
    CREATE TABLE [ctl].[ServerInventoryHistory] (
    [RecordDate] datetime NULL DEFAULT (getdate()),
    [TotalServers] int NULL,
    [HistoryID] int NOT NULL IDENTITY(1,1)
    );
    PRINT 'Created [ctl].[ServerInventoryHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ctl' AND TABLE_NAME = 'ServiceCompliance')
BEGIN
    CREATE TABLE [ctl].[ServiceCompliance] (
    [ComplianceID] int NOT NULL IDENTITY(1,1),
    [ServerName] sysname NOT NULL,
    [ServiceName] sysname NOT NULL,
    [ServiceStatus] varchar(20) NOT NULL,
    [StartType] varchar(20) NULL,
    [IsCompliant] bit NOT NULL,
    [CollectionTime] datetime NOT NULL DEFAULT (getdate())
    );
    PRINT 'Created [ctl].[ServiceCompliance]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ctl' AND TABLE_NAME = 'Stg_ServerInventory')
BEGIN
    CREATE TABLE [ctl].[Stg_ServerInventory] (
    [ServerName] varchar(255) NULL,
    [FQDN] varchar(255) NULL,
    [InstanceName] varchar(255) NULL,
    [DomainName] varchar(255) NULL,
    [Environment] varchar(50) NULL,
    [AppCategory] varchar(100) NULL,
    [SqlEdition] varchar(255) NULL,
    [SqlVersionMajor] int NULL,
    [SqlBuild] varchar(50) NULL,
    [SqlCumulativeUpdate] varchar(50) NULL,
    [WindowsVersion] varchar(255) NULL,
    [WindowsBuild] varchar(50) NULL,
    [TotalMemoryGB] decimal(10,2) NULL,
    [CpuCount] int NULL,
    [IsClustered] bit NULL,
    [IsVM] bit NULL,
    [CaptureTime] datetime NULL DEFAULT (getdate()),
    [SQLVersion] varchar(50) NULL,
    [Edition] varchar(200) NULL,
    [MaxMemoryMB] int NULL,
    [CollectionTime] datetime NULL
    );
    PRINT 'Created [ctl].[Stg_ServerInventory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ctl' AND TABLE_NAME = 'VeeamBackups')
BEGIN
    CREATE TABLE [ctl].[VeeamBackups] (
    [BackupID] int NOT NULL IDENTITY(1,1),
    [JobName] nvarchar(510) NULL,
    [JobType] nvarchar(200) NULL,
    [BackupType] nvarchar(200) NULL,
    [Progress] int NULL,
    [Status] nvarchar(200) NULL,
    [StartTime] datetime2 NULL,
    [EndTime] datetime2 NULL,
    [Result] nvarchar(200) NULL,
    [LoadDate] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [ctl].[VeeamBackups]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ctl' AND TABLE_NAME = 'VeeamJobs')
BEGIN
    CREATE TABLE [ctl].[VeeamJobs] (
    [JobID] int NOT NULL IDENTITY(1,1),
    [VeeamJobID] nvarchar(200) NULL,
    [JobName] nvarchar(510) NULL,
    [JobType] nvarchar(100) NULL,
    [IsDisabled] bit NULL,
    [LastRun] datetime NULL,
    [NextRun] datetime NULL,
    [AddedOn] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [ctl].[VeeamJobs]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ctl' AND TABLE_NAME = 'VeeamJobSessions')
BEGIN
    CREATE TABLE [ctl].[VeeamJobSessions] (
    [SessionID] int NOT NULL IDENTITY(1,1),
    [VeeamSessionID] nvarchar(200) NULL,
    [JobName] nvarchar(510) NULL,
    [VmName] nvarchar(510) NULL,
    [Status] nvarchar(100) NULL,
    [StartTime] datetime NULL,
    [EndTime] datetime NULL,
    [DurationSeconds] int NULL,
    [ResultMessage] nvarchar(MAX) NULL,
    [AddedOn] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [ctl].[VeeamJobSessions]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ctl' AND TABLE_NAME = 'VeeamRestorePoints')
BEGIN
    CREATE TABLE [ctl].[VeeamRestorePoints] (
    [RestorePointID] int NOT NULL IDENTITY(1,1),
    [VmName] nvarchar(400) NULL,
    [BackupType] nvarchar(100) NULL,
    [Created] datetime NULL,
    [StorageRepository] nvarchar(400) NULL,
    [SizeGB] decimal(10,2) NULL,
    [InsertedOn] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [ctl].[VeeamRestorePoints]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ctl' AND TABLE_NAME = 'VeeamServers')
BEGIN
    CREATE TABLE [ctl].[VeeamServers] (
    [VeeamID] int NOT NULL IDENTITY(1,1),
    [ServerName] varchar(128) NOT NULL,
    [Hostname] varchar(256) NULL,
    [PostgreSQLHost] varchar(256) NULL,
    [PostgreSQLPort] int NULL DEFAULT ((5432)),
    [PostgreSQLDatabase] varchar(256) NULL DEFAULT ('VeeamBackup'),
    [ConnectionString] varchar(MAX) NULL,
    [IsActive] bit NULL DEFAULT ((1)),
    [AddedOn] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [ctl].[VeeamServers]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dashboard' AND TABLE_NAME = 'AlertsSummary')
BEGIN
    CREATE TABLE [dashboard].[AlertsSummary] (
    [SummaryID] bigint NOT NULL IDENTITY(1,1),
    [AlertCategory] nvarchar(200) NOT NULL,
    [Severity] nvarchar(100) NULL,
    [ActiveCount] int NULL,
    [AcknowledgedCount] int NULL,
    [ResolvedTodayCount] int NULL,
    [OldestActiveDate] datetime NULL,
    [RefreshedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [dashboard].[AlertsSummary]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dashboard' AND TABLE_NAME = 'ComplianceScorecard')
BEGIN
    CREATE TABLE [dashboard].[ComplianceScorecard] (
    [ScorecardID] bigint NOT NULL IDENTITY(1,1),
    [ComplianceArea] nvarchar(200) NOT NULL,
    [TotalChecks] int NULL,
    [PassedChecks] int NULL,
    [FailedChecks] int NULL,
    [CompliancePercent] decimal(5,2) NULL,
    [Environment] nvarchar(100) NULL,
    [RefreshedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [dashboard].[ComplianceScorecard]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dashboard' AND TABLE_NAME = 'HealthCheckLog')
BEGIN
    CREATE TABLE [dashboard].[HealthCheckLog] (
    [LogID] int NOT NULL IDENTITY(1,1),
    [CheckDate] datetime2 NULL DEFAULT (getdate()),
    [IssueCount] int NULL,
    [Issues] nvarchar(MAX) NULL,
    [AutoRemediated] bit NULL DEFAULT ((0))
    );
    PRINT 'Created [dashboard].[HealthCheckLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dashboard' AND TABLE_NAME = 'MetricsSummary')
BEGIN
    CREATE TABLE [dashboard].[MetricsSummary] (
    [SummaryID] bigint NOT NULL IDENTITY(1,1),
    [MetricCategory] nvarchar(200) NOT NULL,
    [MetricName] nvarchar(200) NOT NULL,
    [MetricValue] decimal(18,4) NULL,
    [MetricUnit] nvarchar(100) NULL,
    [ServerCount] int NULL,
    [Environment] nvarchar(100) NULL,
    [RefreshedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [dashboard].[MetricsSummary]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dashboard' AND TABLE_NAME = 'WatchdogLog')
BEGIN
    CREATE TABLE [dashboard].[WatchdogLog] (
    [LogID] int NOT NULL IDENTITY(1,1),
    [DetectedAt] datetime2 NULL DEFAULT (getdate()),
    [Issues] nvarchar(MAX) NULL,
    [FileSize] bigint NULL,
    [Success] bit NULL
    );
    PRINT 'Created [dashboard].[WatchdogLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'AlertHistory')
BEGIN
    CREATE TABLE [DBAOps].[AlertHistory] (
    [AlertHistoryID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [AlertName] nvarchar(512) NOT NULL,
    [AlertType] nvarchar(100) NULL,
    [Severity] nvarchar(40) NULL,
    [AlertMessage] nvarchar(MAX) NULL,
    [AlertTime] datetime2 NULL DEFAULT (sysdatetime()),
    [IsAcknowledged] bit NULL DEFAULT ((0)),
    [AcknowledgedBy] nvarchar(256) NULL,
    [AcknowledgedTime] datetime2 NULL,
    [Resolution] nvarchar(MAX) NULL,
    [NotificationSent] bit NULL DEFAULT ((0)),
    [NotificationTime] datetime2 NULL
    );
    PRINT 'Created [DBAOps].[AlertHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'BackupTelemetry')
BEGIN
    CREATE TABLE [DBAOps].[BackupTelemetry] (
    [BackupTelemetryID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [BackupType] nvarchar(100) NULL,
    [BackupStartDate] datetime2 NULL,
    [BackupFinishDate] datetime2 NULL,
    [BackupSizeMB] decimal(18,2) NULL,
    [CompressedSizeMB] decimal(18,2) NULL,
    [BackupDurationSeconds] int NULL,
    [BackupPath] nvarchar(1000) NULL,
    [IsSuccessful] bit NULL DEFAULT ((1)),
    [ErrorMessage] nvarchar(MAX) NULL,
    [RecoveryModel] nvarchar(40) NULL,
    [CollectionTime] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [DBAOps].[BackupTelemetry]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'ComplianceChecks')
BEGIN
    CREATE TABLE [DBAOps].[ComplianceChecks] (
    [ComplianceCheckID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [CheckCategory] nvarchar(100) NOT NULL,
    [CheckName] nvarchar(512) NOT NULL,
    [CheckDescription] nvarchar(1000) NULL,
    [ExpectedValue] nvarchar(1000) NULL,
    [ActualValue] nvarchar(1000) NULL,
    [IsCompliant] bit NULL,
    [Severity] nvarchar(40) NULL,
    [RemediationScript] nvarchar(MAX) NULL,
    [CheckTime] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [DBAOps].[ComplianceChecks]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'ConfigurationBaseline')
BEGIN
    CREATE TABLE [DBAOps].[ConfigurationBaseline] (
    [BaselineID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [ConfigName] nvarchar(512) NOT NULL,
    [ConfigDescription] nvarchar(1000) NULL,
    [CurrentValue] sql_variant NULL,
    [BaselineValue] sql_variant NULL,
    [DefaultValue] sql_variant NULL,
    [MinValue] sql_variant NULL,
    [MaxValue] sql_variant NULL,
    [IsDynamic] bit NULL,
    [IsAdvanced] bit NULL,
    [IsInCompliance] bit NULL,
    [CollectionTime] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [DBAOps].[ConfigurationBaseline]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'DatabaseInventory')
BEGIN
    CREATE TABLE [DBAOps].[DatabaseInventory] (
    [DatabaseInventoryID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [DatabaseID] int NULL,
    [OwnerName] nvarchar(256) NULL,
    [CreateDate] datetime NULL,
    [CompatibilityLevel] int NULL,
    [RecoveryModel] nvarchar(40) NULL,
    [StateDesc] nvarchar(120) NULL,
    [SizeMB] decimal(18,2) NULL,
    [DataSizeMB] decimal(18,2) NULL,
    [LogSizeMB] decimal(18,2) NULL,
    [Collation] nvarchar(256) NULL,
    [IsReadOnly] bit NULL DEFAULT ((0)),
    [IsAutoShrink] bit NULL DEFAULT ((0)),
    [IsAutoClose] bit NULL DEFAULT ((0)),
    [PageVerifyOption] nvarchar(40) NULL,
    [CollectionTime] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [DBAOps].[DatabaseInventory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'DiskSpaceHistory')
BEGIN
    CREATE TABLE [DBAOps].[DiskSpaceHistory] (
    [DiskSpaceID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DriveLetter] char(1) NOT NULL,
    [DriveLabel] nvarchar(256) NULL,
    [TotalSpaceGB] decimal(18,2) NULL,
    [FreeSpaceGB] decimal(18,2) NULL,
    [UsedSpaceGB] decimal(18,2) NULL,
    [PercentFree] decimal(5,2) NULL,
    [PercentUsed] decimal(5,2) NULL,
    [CollectionTime] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [DBAOps].[DiskSpaceHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'EvaluationMetrics')
BEGIN
    CREATE TABLE [DBAOps].[EvaluationMetrics] (
    [MetricID] int NOT NULL IDENTITY(1,1),
    [EvaluationDate] datetime2 NULL DEFAULT (sysdatetime()),
    [MetricCategory] nvarchar(200) NULL,
    [MetricName] nvarchar(400) NULL,
    [MetricValue] decimal(10,2) NULL,
    [MetricUnit] nvarchar(100) NULL
    );
    PRINT 'Created [DBAOps].[EvaluationMetrics]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'EvaluationResults')
BEGIN
    CREATE TABLE [DBAOps].[EvaluationResults] (
    [EvaluationID] int NOT NULL IDENTITY(1,1),
    [EvaluationDate] datetime2 NULL DEFAULT (sysdatetime()),
    [ServerName] nvarchar(256) NULL DEFAULT (@@servername),
    [SQLVersion] nvarchar(512) NULL,
    [Category] nvarchar(200) NULL,
    [CheckName] nvarchar(400) NULL,
    [Status] nvarchar(100) NULL,
    [Score] int NULL,
    [Details] nvarchar(MAX) NULL,
    [Recommendation] nvarchar(MAX) NULL
    );
    PRINT 'Created [DBAOps].[EvaluationResults]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'ExpensiveQueries')
BEGIN
    CREATE TABLE [DBAOps].[ExpensiveQueries] (
    [ID] bigint NOT NULL IDENTITY(1,1),
    [CollectionDate] datetime2 NULL DEFAULT (getdate()),
    [ServerName] nvarchar(256) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [QueryID] bigint NULL,
    [TotalCPUTimeMs] decimal(18,2) NULL,
    [TotalDurationMs] decimal(18,2) NULL,
    [TotalLogicalReads] bigint NULL,
    [ExecutionCount] bigint NULL,
    [AvgCPUTimeMs] decimal(18,2) NULL,
    [QueryText] nvarchar(MAX) NULL
    );
    PRINT 'Created [DBAOps].[ExpensiveQueries]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'HybridArchitecture')
BEGIN
    CREATE TABLE [DBAOps].[HybridArchitecture] (
    [Platform] varchar(50) NULL,
    [Enabled] bit NULL,
    [Evidence] varchar(200) NULL,
    [ArchitectureID] int NOT NULL IDENTITY(1,1)
    );
    PRINT 'Created [DBAOps].[HybridArchitecture]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'JobComplianceAudit')
BEGIN
    CREATE TABLE [DBAOps].[JobComplianceAudit] (
    [ID] bigint NOT NULL IDENTITY(1,1),
    [CollectionDate] datetime2 NULL DEFAULT (getdate()),
    [ServerName] nvarchar(256) NULL,
    [JobName] nvarchar(512) NULL,
    [JobEnabled] bit NULL,
    [LastRunDate] datetime NULL,
    [LastRunStatus] nvarchar(40) NULL,
    [NextRunDate] datetime NULL,
    [JobOwner] nvarchar(256) NULL,
    [HasSchedule] bit NULL,
    [HasNotification] bit NULL
    );
    PRINT 'Created [DBAOps].[JobComplianceAudit]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'JobExecutionHistory')
BEGIN
    CREATE TABLE [DBAOps].[JobExecutionHistory] (
    [JobExecutionID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [JobName] nvarchar(512) NOT NULL,
    [JobID] uniqueidentifier NULL,
    [StepID] int NULL,
    [StepName] nvarchar(512) NULL,
    [RunStatus] int NULL,
    [RunStatusDesc] nvarchar(40) NULL,
    [RunDate] datetime2 NULL,
    [RunDurationSeconds] int NULL,
    [RetriesAttempted] int NULL,
    [Message] nvarchar(MAX) NULL,
    [CollectionTime] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [DBAOps].[JobExecutionHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'LoginDriftAudit')
BEGIN
    CREATE TABLE [DBAOps].[LoginDriftAudit] (
    [ID] bigint NOT NULL IDENTITY(1,1),
    [CollectionDate] datetime2 NULL DEFAULT (getdate()),
    [ServerName] nvarchar(256) NULL,
    [LoginName] nvarchar(256) NULL,
    [LoginType] nvarchar(100) NULL,
    [IsDisabled] bit NULL,
    [CreateDate] datetime NULL,
    [ModifyDate] datetime NULL,
    [DefaultDatabase] nvarchar(256) NULL
    );
    PRINT 'Created [DBAOps].[LoginDriftAudit]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'MaintenanceGovernance')
BEGIN
    CREATE TABLE [DBAOps].[MaintenanceGovernance] (
    [MaintenanceType] varchar(20) NOT NULL,
    [Environment] varchar(10) NOT NULL,
    [WindowName] varchar(100) NULL,
    [StartTime] time NOT NULL,
    [EndTime] time NOT NULL,
    [Owner] varchar(100) NULL,
    [Enforced] bit NOT NULL,
    [MaintenanceID] int NOT NULL IDENTITY(1,1)
    );
    PRINT 'Created [DBAOps].[MaintenanceGovernance]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'MaintenanceHistory')
BEGIN
    CREATE TABLE [DBAOps].[MaintenanceHistory] (
    [MaintenanceID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NULL,
    [ObjectName] nvarchar(512) NULL,
    [MaintenanceType] nvarchar(100) NOT NULL,
    [MaintenanceAction] nvarchar(200) NULL,
    [StartTime] datetime2 NULL,
    [EndTime] datetime2 NULL,
    [DurationSeconds] int NULL,
    [CommandExecuted] nvarchar(MAX) NULL,
    [RowsAffected] bigint NULL,
    [IsSuccessful] bit NULL DEFAULT ((1)),
    [ErrorMessage] nvarchar(MAX) NULL
    );
    PRINT 'Created [DBAOps].[MaintenanceHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'MaintenanceOverride')
BEGIN
    CREATE TABLE [DBAOps].[MaintenanceOverride] (
    [OverrideID] int NOT NULL IDENTITY(1,1),
    [MaintenanceType] varchar(20) NULL,
    [Environment] varchar(10) NULL,
    [ApprovedBy] varchar(100) NULL,
    [Reason] varchar(255) NULL,
    [ValidUntil] datetime2 NULL,
    [CreatedAt] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [DBAOps].[MaintenanceOverride]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'OlaDeploymentTracking')
BEGIN
    CREATE TABLE [DBAOps].[OlaDeploymentTracking] (
    [TrackingID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(510) NOT NULL,
    [CommandLogExists] bit NULL DEFAULT ((0)),
    [CommandExecuteExists] bit NULL DEFAULT ((0)),
    [DatabaseBackupExists] bit NULL DEFAULT ((0)),
    [DatabaseIntegrityCheckExists] bit NULL DEFAULT ((0)),
    [IndexOptimizeExists] bit NULL DEFAULT ((0)),
    [BackupJobsConfigured] bit NULL DEFAULT ((0)),
    [IntegrityJobsConfigured] bit NULL DEFAULT ((0)),
    [IndexJobsConfigured] bit NULL DEFAULT ((0)),
    [LastBackupJobRun] datetime NULL,
    [LastIntegrityJobRun] datetime NULL,
    [LastIndexJobRun] datetime NULL,
    [OlaVersion] nvarchar(100) NULL,
    [LastChecked] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [DBAOps].[OlaDeploymentTracking]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'PerformanceDaily')
BEGIN
    CREATE TABLE [DBAOps].[PerformanceDaily] (
    [DailyID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(512) NOT NULL,
    [MetricDate] date NOT NULL,
    [AvgCPUPercent] decimal(5,2) NULL,
    [MaxCPUPercent] decimal(5,2) NULL,
    [AvgMemoryPercent] decimal(5,2) NULL,
    [MaxMemoryPercent] decimal(5,2) NULL,
    [AvgDiskLatencyMs] decimal(10,2) NULL,
    [MaxDiskLatencyMs] decimal(10,2) NULL,
    [CreatedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [DBAOps].[PerformanceDaily]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'PerformanceTelemetry')
BEGIN
    CREATE TABLE [DBAOps].[PerformanceTelemetry] (
    [CaptureTime] datetime2 NULL DEFAULT (sysdatetime()),
    [DatabaseName] sysname NOT NULL,
    [QueryHash] binary NULL,
    [ExecutionCount] bigint NULL,
    [TotalCPU] bigint NULL,
    [TotalDuration] bigint NULL,
    [TotalReads] bigint NULL,
    [DatabaseID] int NULL,
    [ServerName] nvarchar(512) NULL,
    [CPUPercent] decimal(5,2) NULL,
    [MemoryPercent] decimal(5,2) NULL,
    [DiskLatencyMs] decimal(10,2) NULL
    );
    PRINT 'Created [DBAOps].[PerformanceTelemetry]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'PerformanceTelemetryDaily')
BEGIN
    CREATE TABLE [DBAOps].[PerformanceTelemetryDaily] (
    [CaptureDate] date NULL,
    [DatabaseName] sysname NOT NULL,
    [QueryHash] binary NULL,
    [TotalExecutions] bigint NULL,
    [TotalCPU] bigint NULL,
    [TotalDuration] bigint NULL,
    [TotalReads] bigint NULL
    );
    PRINT 'Created [DBAOps].[PerformanceTelemetryDaily]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'PermissionDriftAudit')
BEGIN
    CREATE TABLE [DBAOps].[PermissionDriftAudit] (
    [ID] bigint NOT NULL IDENTITY(1,1),
    [CollectionDate] datetime2 NULL DEFAULT (getdate()),
    [ServerName] nvarchar(256) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [PrincipalName] nvarchar(256) NULL,
    [PrincipalType] nvarchar(100) NULL,
    [PermissionName] nvarchar(256) NULL,
    [PermissionState] nvarchar(40) NULL,
    [ObjectName] nvarchar(512) NULL
    );
    PRINT 'Created [DBAOps].[PermissionDriftAudit]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'ServerHealthTelemetry')
BEGIN
    CREATE TABLE [DBAOps].[ServerHealthTelemetry] (
    [ServerName] sysname NOT NULL,
    [CaptureTime] datetime2 NOT NULL DEFAULT (sysutcdatetime()),
    [CPUPercent] decimal(5,2) NOT NULL,
    [MemoryPercent] decimal(5,2) NOT NULL,
    [DiskLatencyMs] decimal(10,2) NOT NULL
    );
    PRINT 'Created [DBAOps].[ServerHealthTelemetry]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'ServerInventory')
BEGIN
    CREATE TABLE [DBAOps].[ServerInventory] (
    [ServerInventoryID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [InstanceName] nvarchar(512) NULL,
    [Environment] nvarchar(100) NULL,
    [SQLVersion] nvarchar(1000) NULL,
    [SQLEdition] nvarchar(512) NULL,
    [ProductLevel] nvarchar(100) NULL,
    [OSVersion] nvarchar(512) NULL,
    [PhysicalMemoryMB] int NULL,
    [LogicalCPUs] int NULL,
    [IsActive] bit NULL DEFAULT ((1)),
    [IsClustered] bit NULL DEFAULT ((0)),
    [IsAlwaysOn] bit NULL DEFAULT ((0)),
    [CollectionTime] datetime2 NULL DEFAULT (sysdatetime()),
    [LastUpdated] datetime2 NULL DEFAULT (sysdatetime()),
    [Notes] nvarchar(MAX) NULL
    );
    PRINT 'Created [DBAOps].[ServerInventory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'ServerPerformanceDaily')
BEGIN
    CREATE TABLE [DBAOps].[ServerPerformanceDaily] (
    [ServerPerformanceDailyID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] sysname NOT NULL,
    [CaptureDate] date NOT NULL,
    [AvgCPUPercent] decimal(5,2) NULL,
    [MaxCPUPercent] decimal(5,2) NULL,
    [AvgMemoryPercent] decimal(5,2) NULL,
    [MaxMemoryPercent] decimal(5,2) NULL,
    [AvgDiskLatencyMs] decimal(10,2) NULL,
    [MaxDiskLatencyMs] decimal(10,2) NULL,
    [LoadDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [DBAOps].[ServerPerformanceDaily]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'SQLErrorLogs')
BEGIN
    CREATE TABLE [DBAOps].[SQLErrorLogs] (
    [ID] bigint NOT NULL IDENTITY(1,1),
    [CollectionDate] datetime2 NULL DEFAULT (getdate()),
    [ServerName] nvarchar(256) NULL,
    [LogDate] datetime NULL,
    [ProcessInfo] nvarchar(100) NULL,
    [LogText] nvarchar(MAX) NULL,
    [Severity] nvarchar(40) NULL
    );
    PRINT 'Created [DBAOps].[SQLErrorLogs]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'TaniumGovernance')
BEGIN
    CREATE TABLE [DBAOps].[TaniumGovernance] (
    [EventTime] datetime2 NULL,
    [ServerName] sysname NOT NULL,
    [ActionType] varchar(50) NULL,
    [Coordinated] bit NULL,
    [GovernanceID] int NOT NULL IDENTITY(1,1)
    );
    PRINT 'Created [DBAOps].[TaniumGovernance]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'VeeamBackupTelemetry')
BEGIN
    CREATE TABLE [DBAOps].[VeeamBackupTelemetry] (
    [CaptureTime] datetime2 NULL DEFAULT (sysdatetime()),
    [JobName] nvarchar(512) NULL,
    [VMOrDBName] nvarchar(512) NULL,
    [BackupType] nvarchar(100) NULL,
    [Result] nvarchar(100) NULL,
    [DurationSeconds] int NULL,
    [RestorePoints] int NULL,
    [TelemetryID] int NOT NULL IDENTITY(1,1)
    );
    PRINT 'Created [DBAOps].[VeeamBackupTelemetry]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DBAOps' AND TABLE_NAME = 'WaitStatsHistory')
BEGIN
    CREATE TABLE [DBAOps].[WaitStatsHistory] (
    [WaitStatsID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [WaitType] nvarchar(256) NOT NULL,
    [WaitingTasksCount] bigint NULL,
    [WaitTimeMs] bigint NULL,
    [MaxWaitTimeMs] bigint NULL,
    [SignalWaitTimeMs] bigint NULL,
    [WaitCategory] nvarchar(100) NULL,
    [CollectionTime] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [DBAOps].[WaitStatsHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'A2')
BEGIN
    CREATE TABLE [dbo].[A2] (
    [Server] varchar(100) NOT NULL,
    [FQDN] varchar(255) NULL,
    [InstanceName] varchar(100) NULL,
    [DomainName] varchar(100) NULL,
    [Environment] varchar(100) NULL,
    [AppCategory] varchar(100) NULL,
    [SqlEdition] varchar(50) NULL,
    [SqlVersionMajor] int NULL,
    [SqlBuild] varchar(50) NULL,
    [SqlCumulativeUpdate] varchar(50) NULL,
    [WindowsVersion] varchar(50) NULL,
    [WindowsBuild] varchar(50) NULL,
    [TotalMemoryGB] decimal(10,2) NULL,
    [CpuCount] int NULL,
    [IsActive] bit NOT NULL,
    [IsProcessed] bit NOT NULL,
    [IsSQLServer] bit NOT NULL,
    [IsVM] bit NULL,
    [IsClustered] bit NULL,
    [Notes] varchar(MAX) NULL,
    [AddedBy] varchar(100) NULL,
    [LastUpdated] datetime NOT NULL,
    [LastRefreshed] datetime NULL,
    [Retired] datetime NULL,
    [SourceSystem] varchar(50) NULL,
    [CreateDate] datetime NOT NULL,
    [CollectionTime] datetime NULL,
    [MetricsPopulatedSuccessfully] bit NULL,
    [SqlInstanceName] nvarchar(510) NULL,
    [ServerRole] nvarchar(256) NULL,
    [ServerRoleSecondary] nvarchar(510) NULL
    );
    PRINT 'Created [dbo].[A2]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'ADUser_Membership')
BEGIN
    CREATE TABLE [dbo].[ADUser_Membership] (
    [ID] int NOT NULL IDENTITY(1,1),
    [SamAccountName] nvarchar(512) NOT NULL,
    [CN] nvarchar(512) NULL,
    [DisplayName] nvarchar(512) NULL,
    [memberof] nvarchar(1024) NULL,
    [Created] datetime NULL,
    [Modified] datetime NULL
    );
    PRINT 'Created [dbo].[ADUser_Membership]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'ADUsers')
BEGIN
    CREATE TABLE [dbo].[ADUsers] (
    [SamAccountName] nvarchar(512) NOT NULL,
    [pwdlastset] datetime NULL,
    [pwdlastset_int] bigint NULL,
    [CN] nvarchar(512) NULL,
    [Company] nvarchar(512) NULL,
    [Department] nvarchar(512) NULL,
    [DisplayName] nvarchar(512) NULL,
    [Division] nvarchar(512) NULL,
    [EmployeeID] nvarchar(100) NULL,
    [employeeType] nvarchar(512) NULL,
    [GivenName] nvarchar(512) NULL,
    [Initials] nvarchar(20) NULL,
    [mail] nvarchar(512) NULL,
    [mobile] nvarchar(100) NULL,
    [MobilePhone] nvarchar(100) NULL,
    [photo] nvarchar(MAX) NULL,
    [physicalDeliveryOfficeName] nvarchar(512) NULL,
    [sn] nvarchar(512) NULL,
    [OfficePhone] nvarchar(100) NULL,
    [Title] nvarchar(512) NULL,
    [extensionAttribute1] nvarchar(512) NULL,
    [extensionAttribute2] nvarchar(512) NULL,
    [extensionAttribute3] nvarchar(512) NULL,
    [extensionAttribute4] nvarchar(512) NULL,
    [extensionAttribute5] nvarchar(512) NULL,
    [MemberOf] nvarchar(MAX) NULL,
    [UserPrincipalName] nvarchar(512) NULL,
    [userAccountControl] int NULL,
    [Created] datetime NULL,
    [Modified] datetime NULL
    );
    PRINT 'Created [dbo].[ADUsers]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'ADUsers_Load')
BEGIN
    CREATE TABLE [dbo].[ADUsers_Load] (
    [SamAccountName] nvarchar(512) NOT NULL,
    [pwdlastset] datetime NULL,
    [pwdlastset_int] bigint NULL,
    [CN] nvarchar(512) NULL,
    [Company] nvarchar(512) NULL,
    [Department] nvarchar(512) NULL,
    [DisplayName] nvarchar(512) NULL,
    [Division] nvarchar(512) NULL,
    [EmployeeID] nvarchar(100) NULL,
    [employeeType] nvarchar(512) NULL,
    [GivenName] nvarchar(512) NULL,
    [Initials] nvarchar(20) NULL,
    [mail] nvarchar(512) NULL,
    [mobile] nvarchar(100) NULL,
    [MobilePhone] nvarchar(100) NULL,
    [photo] nvarchar(MAX) NULL,
    [physicalDeliveryOfficeName] nvarchar(512) NULL,
    [sn] nvarchar(512) NULL,
    [OfficePhone] nvarchar(100) NULL,
    [Title] nvarchar(512) NULL,
    [extensionAttribute1] nvarchar(512) NULL,
    [extensionAttribute2] nvarchar(512) NULL,
    [extensionAttribute3] nvarchar(512) NULL,
    [extensionAttribute4] nvarchar(512) NULL,
    [extensionAttribute5] nvarchar(512) NULL,
    [MemberOf] nvarchar(MAX) NULL,
    [UserPrincipalName] nvarchar(512) NULL,
    [userAccountControl] int NULL
    );
    PRINT 'Created [dbo].[ADUsers_Load]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'BackupHistory')
BEGIN
    CREATE TABLE [dbo].[BackupHistory] (
    [BackupHistoryID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [BackupType] char(1) NOT NULL,
    [BackupStartDate] datetime2 NOT NULL,
    [BackupFinishDate] datetime2 NOT NULL,
    [BackupSizeBytes] bigint NULL,
    [CompressedSizeBytes] bigint NULL,
    [BackupPath] nvarchar(1000) NULL,
    [IsSuccessful] bit NULL DEFAULT ((1)),
    [ErrorMessage] nvarchar(MAX) NULL,
    [CollectedAt] datetime2 NULL DEFAULT (getdate())
    );
    PRINT 'Created [dbo].[BackupHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'CollectorHealth')
BEGIN
    CREATE TABLE [dbo].[CollectorHealth] (
    [ID] int NOT NULL IDENTITY(1,1),
    [ServerName] varchar(200) NULL,
    [Status] varchar(50) NULL,
    [ErrorMessage] varchar(MAX) NULL,
    [CollectionTime] datetime NOT NULL DEFAULT (getdate())
    );
    PRINT 'Created [dbo].[CollectorHealth]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'CollectorLog')
BEGIN
    CREATE TABLE [dbo].[CollectorLog] (
    [LogID] int NOT NULL IDENTITY(1,1),
    [RunDate] datetime NULL DEFAULT (getdate()),
    [SqlInstance] varchar(128) NULL,
    [Status] varchar(20) NULL,
    [Message] varchar(MAX) NULL
    );
    PRINT 'Created [dbo].[CollectorLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'CommandLog')
BEGIN
    CREATE TABLE [dbo].[CommandLog] (
    [ID] int NOT NULL IDENTITY(1,1),
    [DatabaseName] sysname NULL,
    [SchemaName] sysname NULL,
    [ObjectName] sysname NULL,
    [ObjectType] char(2) NULL,
    [IndexName] sysname NULL,
    [IndexType] tinyint NULL,
    [StatisticsName] sysname NULL,
    [PartitionNumber] int NULL,
    [ExtendedInfo] xml NULL,
    [Command] nvarchar(MAX) NOT NULL,
    [CommandType] nvarchar(120) NOT NULL,
    [StartTime] datetime2 NOT NULL,
    [EndTime] datetime2 NULL,
    [ErrorNumber] int NULL,
    [ErrorMessage] nvarchar(MAX) NULL
    );
    PRINT 'Created [dbo].[CommandLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'CommandLog_Central')
BEGIN
    CREATE TABLE [dbo].[CommandLog_Central] (
    [CentralID] bigint NOT NULL IDENTITY(1,1),
    [SourceServer] nvarchar(256) NOT NULL,
    [CollectedDate] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [OriginalID] int NOT NULL,
    [DatabaseName] sysname NULL,
    [SchemaName] sysname NULL,
    [ObjectName] sysname NULL,
    [ObjectType] char(2) NULL,
    [IndexName] sysname NULL,
    [IndexType] tinyint NULL,
    [StatisticsName] sysname NULL,
    [PartitionNumber] int NULL,
    [ExtendedInfo] xml NULL,
    [Command] nvarchar(MAX) NOT NULL,
    [CommandType] nvarchar(120) NOT NULL,
    [StartTime] datetime2 NOT NULL,
    [EndTime] datetime2 NULL,
    [ErrorNumber] int NULL,
    [ErrorMessage] nvarchar(MAX) NULL,
    [DurationSeconds] int NULL
    );
    PRINT 'Created [dbo].[CommandLog_Central]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'Config')
BEGIN
    CREATE TABLE [dbo].[Config] (
    [ConfigKey] nvarchar(200) NOT NULL,
    [ConfigValue] nvarchar(MAX) NOT NULL,
    [ModifiedOn] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [dbo].[Config]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'Configuration')
BEGIN
    CREATE TABLE [dbo].[Configuration] (
    [ConfigID] int NOT NULL IDENTITY(1,1),
    [ConfigKey] nvarchar(200) NOT NULL,
    [ConfigValue] nvarchar(1000) NULL,
    [Description] nvarchar(1000) NULL,
    [ModifiedDate] datetime2 NULL DEFAULT (getdate()),
    [ModifiedBy] nvarchar(200) NULL
    );
    PRINT 'Created [dbo].[Configuration]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'DBAOps_AuditFindings')
BEGIN
    CREATE TABLE [dbo].[DBAOps_AuditFindings] (
    [AuditID] int NOT NULL IDENTITY(1,1),
    [AuditRunTime] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [Category] nvarchar(200) NOT NULL,
    [Issue] nvarchar(1000) NOT NULL,
    [Severity] nvarchar(40) NOT NULL,
    [Impact] nvarchar(1000) NULL,
    [Recommendation] nvarchar(2000) NULL
    );
    PRINT 'Created [dbo].[DBAOps_AuditFindings]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'DBAOps_JobScheduleMap')
BEGIN
    CREATE TABLE [dbo].[DBAOps_JobScheduleMap] (
    [JobName] nvarchar(510) NOT NULL,
    [ScheduleName] nvarchar(510) NOT NULL,
    [ExpectedFrequency] nvarchar(100) NULL,
    [CreatedDate] datetime NOT NULL DEFAULT (getdate()),
    [LastUpdated] datetime NOT NULL DEFAULT (getdate())
    );
    PRINT 'Created [dbo].[DBAOps_JobScheduleMap]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'DBAOps_JobSeverity')
BEGIN
    CREATE TABLE [dbo].[DBAOps_JobSeverity] (
    [JobName] nvarchar(400) NOT NULL,
    [SeverityLevel] int NOT NULL,
    [UpdatedDate] datetime NULL DEFAULT (getdate()),
    [UpdatedBy] nvarchar(100) NULL DEFAULT (suser_sname())
    );
    PRINT 'Created [dbo].[DBAOps_JobSeverity]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'DBAOps_ValidationDashboard')
BEGIN
    CREATE TABLE [dbo].[DBAOps_ValidationDashboard] (
    [ID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [ValidationDate] datetime2 NULL DEFAULT (sysdatetime()),
    [ValidationResult] nvarchar(100) NULL,
    [Details] nvarchar(MAX) NULL
    );
    PRINT 'Created [dbo].[DBAOps_ValidationDashboard]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'DDL_AuditEvents')
BEGIN
    CREATE TABLE [dbo].[DDL_AuditEvents] (
    [AuditID] bigint NOT NULL IDENTITY(1,1),
    [EventName] varchar(50) NOT NULL,
    [DatabaseName] sysname NOT NULL,
    [ObjectName] sysname NOT NULL,
    [LoginName] sysname NOT NULL,
    [EventTime] datetime2 NOT NULL,
    [LoadTime] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [SourceFile] varchar(260) NULL
    );
    PRINT 'Created [dbo].[DDL_AuditEvents]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'dim_Servers')
BEGIN
    CREATE TABLE [dbo].[dim_Servers] (
    [ServerID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [Environment] nvarchar(100) NULL,
    [DataCenter] nvarchar(100) NULL,
    [ServerType] nvarchar(100) NULL,
    [OSVersion] nvarchar(200) NULL,
    [SQLVersion] nvarchar(200) NULL,
    [IsActive] bit NOT NULL DEFAULT ((1)),
    [IsMonitored] bit NOT NULL DEFAULT ((1)),
    [Latitude] decimal(10,8) NULL,
    [Longitude] decimal(11,8) NULL,
    [IPAddress] nvarchar(100) NULL,
    [PrimaryOwner] nvarchar(200) NULL,
    [BackupOwner] nvarchar(200) NULL,
    [Description] nvarchar(1000) NULL,
    [CreatedDate] datetime2 NOT NULL DEFAULT (getdate()),
    [ModifiedDate] datetime2 NOT NULL DEFAULT (getdate()),
    [Edition] nvarchar(200) NULL
    );
    PRINT 'Created [dbo].[dim_Servers]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'DiskSpaceAlerts')
BEGIN
    CREATE TABLE [dbo].[DiskSpaceAlerts] (
    [AlertID] int NOT NULL IDENTITY(1,1),
    [ServerName] varchar(256) NOT NULL,
    [DriveLetter] char(1) NOT NULL,
    [FreeSpaceGB] decimal(18,2) NULL,
    [FreeSpacePercent] decimal(5,2) NULL,
    [AlertSeverity] varchar(20) NULL,
    [AlertTime] datetime2 NULL DEFAULT (sysdatetime()),
    [Acknowledged] bit NULL DEFAULT ((0)),
    [AcknowledgedBy] varchar(256) NULL,
    [AcknowledgedAt] datetime2 NULL
    );
    PRINT 'Created [dbo].[DiskSpaceAlerts]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'DiskSpaceExclusions')
BEGIN
    CREATE TABLE [dbo].[DiskSpaceExclusions] (
    [ExclusionID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DriveLetter] char(1) NOT NULL,
    [Reason] nvarchar(1000) NULL,
    [ExcludedBy] nvarchar(200) NULL,
    [ExcludedDate] datetime2 NULL DEFAULT (getdate()),
    [IsActive] bit NULL DEFAULT ((1))
    );
    PRINT 'Created [dbo].[DiskSpaceExclusions]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'DiskSpaceInventory')
BEGIN
    CREATE TABLE [dbo].[DiskSpaceInventory] (
    [DiskSpaceID] int NOT NULL IDENTITY(1,1),
    [ServerName] varchar(256) NOT NULL,
    [DriveLetter] char(1) NOT NULL,
    [VolumeName] nvarchar(512) NULL,
    [TotalSizeGB] decimal(18,2) NULL,
    [FreeSpaceGB] decimal(18,2) NULL,
    [FreeSpacePercent] decimal(5,2) NULL,
    [CollectedAt] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [dbo].[DiskSpaceInventory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'EmailTemplates')
BEGIN
    CREATE TABLE [dbo].[EmailTemplates] (
    [TemplateName] nvarchar(200) NOT NULL,
    [HtmlContent] nvarchar(MAX) NULL,
    [SubjectLine] nvarchar(510) NULL,
    [BodyHTML] nvarchar(MAX) NULL
    );
    PRINT 'Created [dbo].[EmailTemplates]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'fact_Alerts')
BEGIN
    CREATE TABLE [dbo].[fact_Alerts] (
    [AlertID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [AlertType] nvarchar(200) NULL,
    [AlertMessage] nvarchar(MAX) NULL,
    [Severity] nvarchar(40) NULL,
    [AlertTime] datetime2 NULL DEFAULT (sysutcdatetime()),
    [Processed] bit NULL DEFAULT ((0)),
    [AlertSeverity] varchar(50) NULL,
    [CaptureTime] datetime NULL,
    [ProcessedTime] datetime2 NULL,
    [ProcessedBy] nvarchar(200) NULL,
    [ProcessedDate] datetime2 NULL
    );
    PRINT 'Created [dbo].[fact_Alerts]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'FACT_CollectorHealth')
BEGIN
    CREATE TABLE [dbo].[FACT_CollectorHealth] (
    [HealthID] int NOT NULL IDENTITY(1,1),
    [CollectorName] varchar(100) NULL,
    [ServerName] varchar(200) NULL,
    [StartTime] datetime NULL,
    [EndTime] datetime NULL,
    [DurationSeconds] int NULL,
    [Status] varchar(50) NULL,
    [ErrorMessage] varchar(MAX) NULL
    );
    PRINT 'Created [dbo].[FACT_CollectorHealth]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'fact_DailyAlertSummary')
BEGIN
    CREATE TABLE [dbo].[fact_DailyAlertSummary] (
    [SummaryDate] date NOT NULL,
    [TotalAlerts] int NULL,
    [HighAlerts] int NULL,
    [MediumAlerts] int NULL,
    [LowAlerts] int NULL,
    [UniqueServers] int NULL,
    [ReportGeneratedOn] datetime NOT NULL DEFAULT (getdate())
    );
    PRINT 'Created [dbo].[fact_DailyAlertSummary]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'fact_DailyPerformanceSummary')
BEGIN
    CREATE TABLE [dbo].[fact_DailyPerformanceSummary] (
    [SummaryID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [SummaryDate] date NOT NULL,
    [AvgCPUPercent] decimal(5,2) NULL,
    [MaxCPUPercent] decimal(5,2) NULL,
    [AvgMemoryPercent] decimal(5,2) NULL,
    [MaxMemoryPercent] decimal(5,2) NULL,
    [AvgDiskLatencyMs] decimal(10,2) NULL,
    [MaxDiskLatencyMs] decimal(10,2) NULL,
    [TotalBatchRequests] bigint NULL,
    [TotalCompilations] bigint NULL,
    [PageLifeExpectancy] int NULL,
    [BufferCacheHitRatio] decimal(5,2) NULL,
    [CollectionTime] datetime NULL DEFAULT (getdate()),
    [InsertedAt] datetime NULL DEFAULT (getdate()),
    [AvgMemoryUsedMB] decimal(18,2) NULL,
    [MaxMemoryUsedMB] decimal(18,2) NULL,
    [AvgBatchRequests] decimal(18,2) NULL,
    [MaxBatchRequests] decimal(18,2) NULL,
    [AvgPLE] int NULL,
    [MinPLE] int NULL
    );
    PRINT 'Created [dbo].[fact_DailyPerformanceSummary]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'fact_DatabaseFiles')
BEGIN
    CREATE TABLE [dbo].[fact_DatabaseFiles] (
    [FileFactID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] sysname NOT NULL,
    [DatabaseName] sysname NOT NULL,
    [FileLogicalName] sysname NOT NULL,
    [FileType] varchar(20) NULL,
    [FileGroupName] sysname NULL,
    [FilePath] nvarchar(8000) NULL,
    [SizeMB] decimal(18,2) NULL,
    [MaxSizeMB] decimal(18,2) NULL,
    [GrowthMB] decimal(18,2) NULL,
    [IsPercentGrowth] bit NULL,
    [DriveLetter] char(1) NULL,
    [CaptureTime] datetime2 NULL DEFAULT (sysutcdatetime())
    );
    PRINT 'Created [dbo].[fact_DatabaseFiles]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'fact_DatabaseInventory')
BEGIN
    CREATE TABLE [dbo].[fact_DatabaseInventory] (
    [InventoryFactID] int NOT NULL IDENTITY(1,1),
    [ServerName] varchar(200) NOT NULL,
    [DatabaseName] varchar(200) NOT NULL,
    [StateDesc] varchar(50) NULL,
    [RecoveryModel] varchar(20) NULL,
    [CompatibilityLevel] int NULL,
    [SizeMB] decimal(18,2) NULL,
    [CreateDate] datetime2 NULL,
    [CaptureTime] datetime2 NOT NULL
    );
    PRINT 'Created [dbo].[fact_DatabaseInventory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'fact_DatabaseInventory_Archive')
BEGIN
    CREATE TABLE [dbo].[fact_DatabaseInventory_Archive] (
    [ArchiveID] int NOT NULL IDENTITY(1,1),
    [InventoryFactID] int NULL,
    [ServerName] varchar(256) NULL,
    [DatabaseName] varchar(256) NULL,
    [StateDesc] varchar(60) NULL,
    [RecoveryModel] varchar(60) NULL,
    [CompatibilityLevel] int NULL,
    [SizeMB] decimal(18,2) NULL,
    [CreateDate] datetime2 NULL,
    [CaptureTime] datetime2 NULL,
    [ArchivedAt] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [dbo].[fact_DatabaseInventory_Archive]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'fact_DiskInventory')
BEGIN
    CREATE TABLE [dbo].[fact_DiskInventory] (
    [DiskID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [DriveLetter] nvarchar(20) NULL,
    [VolumeLabel] nvarchar(256) NULL,
    [TotalSizeGB] decimal(18,2) NULL,
    [FreeSpaceGB] decimal(18,2) NULL,
    [CaptureTime] datetime2 NOT NULL DEFAULT (sysutcdatetime())
    );
    PRINT 'Created [dbo].[fact_DiskInventory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'fact_DiskSpace')
BEGIN
    CREATE TABLE [dbo].[fact_DiskSpace] (
    [DiskSpaceID] int NOT NULL IDENTITY(1,1),
    [ServerID] int NOT NULL,
    [DriveLetter] varchar(10) NOT NULL,
    [TotalSpaceGB] decimal(18,2) NOT NULL,
    [FreeSpaceGB] decimal(18,2) NOT NULL,
    [FreePercent] decimal(5,2) NOT NULL,
    [CollectionTimeUTC] datetime NOT NULL DEFAULT (getutcdate())
    );
    PRINT 'Created [dbo].[fact_DiskSpace]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'FACT_ErrorLog')
BEGIN
    CREATE TABLE [dbo].[FACT_ErrorLog] (
    [ErrorLogID] int NOT NULL IDENTITY(1,1),
    [LogTime] datetime2 NOT NULL DEFAULT (sysutcdatetime()),
    [LogLevel] nvarchar(40) NOT NULL,
    [Category] nvarchar(200) NULL,
    [MessageText] nvarchar(MAX) NOT NULL,
    [ServerName] nvarchar(256) NULL,
    [AdditionalInfo] nvarchar(MAX) NULL
    );
    PRINT 'Created [dbo].[FACT_ErrorLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'fact_InstanceInventory')
BEGIN
    CREATE TABLE [dbo].[fact_InstanceInventory] (
    [InventoryID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [CPUCount] int NULL,
    [MaxServerMemoryMB] int NULL,
    [MinServerMemoryMB] int NULL,
    [TotalMemoryMB] int NULL,
    [MaxDOP] int NULL,
    [CostThreshold] int NULL,
    [TempDBFileCount] int NULL,
    [TempDBFileSizeMB] decimal(18,2) NULL,
    [TempDBGrowthMB] decimal(18,2) NULL,
    [SQLServiceAccount] nvarchar(400) NULL,
    [SQLStartTime] datetime NULL,
    [CaptureTime] datetime2 NOT NULL DEFAULT (sysutcdatetime())
    );
    PRINT 'Created [dbo].[fact_InstanceInventory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'fact_IOStats')
BEGIN
    CREATE TABLE [dbo].[fact_IOStats] (
    [IOID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] sysname NOT NULL,
    [DatabaseName] sysname NOT NULL,
    [FileLogicalName] nvarchar(600) NULL,
    [Reads] bigint NULL,
    [Writes] bigint NULL,
    [ReadMB] decimal(18,2) NULL,
    [WriteMB] decimal(18,2) NULL,
    [IoStallMS] bigint NULL,
    [CaptureTime] datetime2 NULL DEFAULT (sysutcdatetime())
    );
    PRINT 'Created [dbo].[fact_IOStats]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'fact_PerformanceSnapshot')
BEGIN
    CREATE TABLE [dbo].[fact_PerformanceSnapshot] (
    [SnapshotID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [SqlCpuPercent] int NULL,
    [SystemIdle] int NULL,
    [AvailableMemoryMB] bigint NULL,
    [TotalMemoryMB] bigint NULL,
    [TargetServerMemoryMB] bigint NULL,
    [SqlMemoryUsedMB] bigint NULL,
    [PageLifeExpectancy] bigint NULL,
    [BatchRequestsPerSec] bigint NULL,
    [Connections] int NULL,
    [SnapshotTime] datetime NULL DEFAULT (getdate()),
    [SqlCommittedMemoryMB] int NULL,
    [SqlTargetMemoryMB] int NULL
    );
    PRINT 'Created [dbo].[fact_PerformanceSnapshot]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'FACT_ServerHealth')
BEGIN
    CREATE TABLE [dbo].[FACT_ServerHealth] (
    [ID] bigint NOT NULL IDENTITY(1,1),
    [CaptureTime] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [ServerName] sysname NOT NULL,
    [CPU_Utilization] decimal(10,2) NULL,
    [CPU_SignalWaitPct] decimal(10,2) NULL,
    [RunnableTasksCount] int NULL,
    [Scheduler_Total_CPU_Usage_MS] bigint NULL,
    [Memory_PLE] int NULL,
    [Memory_GrantsPending] int NULL,
    [Memory_TotalMB] decimal(18,2) NULL,
    [Memory_UsedMB] decimal(18,2) NULL,
    [SQL_Memory_Model] int NULL,
    [SQL_Memory_Model_Desc] varchar(200) NULL,
    [Process_Physical_Memory_Low] bit NULL,
    [Process_Virtual_Memory_Low] bit NULL,
    [TempDB_UsageMB] decimal(18,2) NULL,
    [TempDB_VersionStoreMB] decimal(18,2) NULL,
    [ActiveSessions] int NULL,
    [BlockingSessions] int NULL,
    [LongRunningRequests] int NULL,
    [ErrorLog_CriticalCount] int NULL,
    [InstanceVersion] varchar(200) NULL,
    [Edition] varchar(200) NULL,
    [UptimeHours] int NULL,
    [BackupAge_Full_Hours] int NULL,
    [BackupAge_Diff_Hours] int NULL,
    [BackupAge_Log_Hours] int NULL,
    [Memory_PressureFlag] int NOT NULL,
    [CPU_PressureFlag] int NOT NULL
    );
    PRINT 'Created [dbo].[FACT_ServerHealth]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'FACT_ServerHealth_Archive')
BEGIN
    CREATE TABLE [dbo].[FACT_ServerHealth_Archive] (
    [ID] bigint NOT NULL IDENTITY(1,1),
    [CaptureTime] datetime2 NOT NULL,
    [ServerName] nvarchar(256) NOT NULL,
    [CPU_Utilization] decimal(10,2) NULL,
    [CPU_SignalWaitPct] decimal(10,2) NULL,
    [RunnableTasksCount] int NULL,
    [Scheduler_Total_CPU_Usage_MS] bigint NULL,
    [Memory_PLE] int NULL,
    [Memory_GrantsPending] int NULL,
    [Memory_TotalMB] decimal(18,2) NULL,
    [Memory_UsedMB] decimal(18,2) NULL,
    [SQL_Memory_Model] int NULL,
    [SQL_Memory_Model_Desc] varchar(200) NULL,
    [Process_Physical_Memory_Low] bit NULL,
    [Process_Virtual_Memory_Low] bit NULL,
    [TempDB_UsageMB] decimal(18,2) NULL,
    [TempDB_VersionStoreMB] decimal(18,2) NULL,
    [ActiveSessions] int NULL,
    [BlockingSessions] int NULL,
    [LongRunningRequests] int NULL,
    [ErrorLog_CriticalCount] int NULL,
    [InstanceVersion] varchar(200) NULL,
    [Edition] varchar(200) NULL,
    [UptimeHours] int NULL,
    [BackupAge_Full_Hours] int NULL,
    [BackupAge_Diff_Hours] int NULL,
    [BackupAge_Log_Hours] int NULL,
    [ArchivedDate] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [dbo].[FACT_ServerHealth_Archive]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'fact_TempDBUsage')
BEGIN
    CREATE TABLE [dbo].[fact_TempDBUsage] (
    [TempID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] sysname NOT NULL,
    [SessionID] int NULL,
    [TaskAllocMB] decimal(18,2) NULL,
    [TaskDeallocMB] decimal(18,2) NULL,
    [UserObjMB] decimal(18,2) NULL,
    [InternalObjMB] decimal(18,2) NULL,
    [CaptureTime] datetime2 NULL DEFAULT (sysutcdatetime())
    );
    PRINT 'Created [dbo].[fact_TempDBUsage]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'FACT_UnreachableServers')
BEGIN
    CREATE TABLE [dbo].[FACT_UnreachableServers] (
    [ID] int NOT NULL IDENTITY(1,1),
    [ServerName] varchar(200) NULL,
    [AttemptTime] datetime NULL DEFAULT (getdate()),
    [ErrorMessage] varchar(MAX) NULL
    );
    PRINT 'Created [dbo].[FACT_UnreachableServers]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'fact_WaitStats')
BEGIN
    CREATE TABLE [dbo].[fact_WaitStats] (
    [WaitID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] sysname NOT NULL,
    [WaitType] nvarchar(400) NULL,
    [WaitTimeMS] bigint NULL,
    [SignalWaitMS] bigint NULL,
    [WaitingTasks] bigint NULL,
    [CaptureTime] datetime2 NULL DEFAULT (sysutcdatetime()),
    [MaxWaitTimeMS] bigint NULL,
    [SignalWaitTimeMS] bigint NULL
    );
    PRINT 'Created [dbo].[fact_WaitStats]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'factJobScheduleDriftAlertQueue')
BEGIN
    CREATE TABLE [dbo].[factJobScheduleDriftAlertQueue] (
    [AlertID] int NOT NULL IDENTITY(1,1),
    [DriftID] int NOT NULL,
    [JobName] nvarchar(510) NOT NULL,
    [ExpectedSchedule] nvarchar(510) NULL,
    [ActualSchedule] nvarchar(510) NULL,
    [ComplianceStatus] nvarchar(100) NULL,
    [HealAction] nvarchar(510) NULL,
    [CaptureDate] datetime NOT NULL,
    [AlertStatus] nvarchar(40) NULL DEFAULT ('Pending'),
    [CreatedDate] datetime NULL DEFAULT (getdate()),
    [ProcessedDate] datetime NULL,
    [DetectedTime] datetime2 NULL
    );
    PRINT 'Created [dbo].[factJobScheduleDriftAlertQueue]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'factJobScheduleDriftAudit')
BEGIN
    CREATE TABLE [dbo].[factJobScheduleDriftAudit] (
    [AuditID] int NOT NULL IDENTITY(1,1),
    [AlertID] int NOT NULL,
    [JobName] nvarchar(510) NOT NULL,
    [ExpectedSchedule] nvarchar(510) NULL,
    [ActualSchedule] nvarchar(510) NULL,
    [ComplianceStatus] nvarchar(100) NULL,
    [HealAction] nvarchar(510) NULL,
    [DetectedTime] datetime2 NOT NULL,
    [ProcessedTime] datetime2 NULL,
    [EmailSentTime] datetime2 NULL,
    [SentByProcedure] nvarchar(510) NOT NULL DEFAULT ('usp_DBAOps_SendDriftAlert'),
    [InsertedDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [dbo].[factJobScheduleDriftAudit]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'factJobScheduleDriftLog')
BEGIN
    CREATE TABLE [dbo].[factJobScheduleDriftLog] (
    [DriftID] int NOT NULL IDENTITY(1,1),
    [JobName] nvarchar(510) NULL,
    [ExpectedSchedule] nvarchar(510) NULL,
    [ActualSchedule] nvarchar(510) NULL,
    [ComplianceStatus] nvarchar(100) NULL,
    [HealAction] nvarchar(510) NULL,
    [CaptureDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [dbo].[factJobScheduleDriftLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'JobDurationHistory')
BEGIN
    CREATE TABLE [dbo].[JobDurationHistory] (
    [DurationID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [JobName] nvarchar(512) NOT NULL,
    [RunDateTime] datetime2 NOT NULL,
    [DurationSeconds] int NOT NULL,
    [RunStatus] int NULL,
    [CollectedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [dbo].[JobDurationHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'JobFailureHistory')
BEGIN
    CREATE TABLE [dbo].[JobFailureHistory] (
    [FailureID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [JobName] nvarchar(512) NOT NULL,
    [StepName] nvarchar(512) NULL,
    [FailedAt] datetime2 NOT NULL,
    [ErrorMessage] nvarchar(MAX) NULL,
    [NotificationSent] bit NOT NULL DEFAULT ((0)),
    [AcknowledgedBy] nvarchar(256) NULL,
    [RootCause] nvarchar(1000) NULL,
    [Resolution] nvarchar(1000) NULL,
    [CollectedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [dbo].[JobFailureHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'JobIntegrityAlerts')
BEGIN
    CREATE TABLE [dbo].[JobIntegrityAlerts] (
    [AlertID] int NOT NULL IDENTITY(1,1),
    [SQLInstance] varchar(128) NULL,
    [JobName] varchar(255) NULL,
    [IssueDetected] varchar(200) NULL,
    [FirstDetected] datetime NOT NULL DEFAULT (getdate()),
    [LastAlerted] datetime NOT NULL DEFAULT (getdate())
    );
    PRINT 'Created [dbo].[JobIntegrityAlerts]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'JobIntegrityAudit')
BEGIN
    CREATE TABLE [dbo].[JobIntegrityAudit] (
    [AuditID] int NOT NULL IDENTITY(1,1),
    [CaptureDate] datetime NOT NULL DEFAULT (getdate()),
    [SQLInstance] nvarchar(256) NULL,
    [JobName] nvarchar(512) NULL,
    [ScheduleName] nvarchar(512) NULL,
    [IsScheduled] bit NULL,
    [IsScheduleEnabled] bit NULL,
    [IsJobEnabled] bit NULL,
    [HasDuplicateSched] bit NULL,
    [LastRunDate] datetime NULL,
    [LastRunStatus] nvarchar(100) NULL,
    [RunDuration] int NULL,
    [NextRunDate] datetime NULL,
    [IssueDetected] nvarchar(1000) NULL
    );
    PRINT 'Created [dbo].[JobIntegrityAudit]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'MaintenanceServers')
BEGIN
    CREATE TABLE [dbo].[MaintenanceServers] (
    [ServerID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [LinkedServerName] nvarchar(256) NULL,
    [Environment] nvarchar(40) NULL,
    [IsActive] bit NOT NULL DEFAULT ((1)),
    [LastCollectionDate] datetime2 NULL,
    [LastCollectionStatus] nvarchar(100) NULL,
    [LastErrorMessage] nvarchar(MAX) NULL,
    [CreatedDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [dbo].[MaintenanceServers]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'PerformanceComplianceInventory')
BEGIN
    CREATE TABLE [dbo].[PerformanceComplianceInventory] (
    [ID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [SQLVersion] nvarchar(100) NULL,
    [Edition] nvarchar(200) NULL,
    [CpuCount] int NULL,
    [MaxServerMemoryGB] decimal(10,2) NULL,
    [TotalMemoryGB] decimal(10,2) NULL,
    [TempDBFiles] int NULL,
    [TempDBDataSizeMB] decimal(18,2) NULL,
    [TempDBLogSizeMB] decimal(18,2) NULL,
    [PageLifeExpectancy] bigint NULL,
    [SignalWaitPercent] decimal(10,2) NULL,
    [WaitsTop1] nvarchar(400) NULL,
    [WaitsTop2] nvarchar(400) NULL,
    [WaitsTop3] nvarchar(400) NULL,
    [CollectionTime] datetime NOT NULL DEFAULT (getdate())
    );
    PRINT 'Created [dbo].[PerformanceComplianceInventory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'ScriptStaging')
BEGIN
    CREATE TABLE [dbo].[ScriptStaging] (
    [ID] int NOT NULL IDENTITY(1,1),
    [Line] nvarchar(8000) NULL
    );
    PRINT 'Created [dbo].[ScriptStaging]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'ServerGroups')
BEGIN
    CREATE TABLE [dbo].[ServerGroups] (
    [ServerName] sysname NOT NULL,
    [ServerGroup] varchar(50) NOT NULL
    );
    PRINT 'Created [dbo].[ServerGroups]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'ServerInventory')
BEGIN
    CREATE TABLE [dbo].[ServerInventory] (
    [ServerInventoryID] int NOT NULL IDENTITY(1,1),
    [ServerName] varchar(200) NULL,
    [InstanceName] varchar(200) NULL,
    [DomainName] varchar(200) NULL,
    [FQDN] varchar(300) NULL,
    [SQLVersion] varchar(50) NULL,
    [SQLVersionMajor] int NULL,
    [SQLBuild] varchar(50) NULL,
    [SQLCumulativeUpdate] varchar(50) NULL,
    [Edition] varchar(200) NULL,
    [Collation] varchar(200) NULL,
    [IsClustered] bit NULL,
    [IsAGNode] bit NULL,
    [AGRole] varchar(50) NULL,
    [CpuCount] int NULL,
    [MaxMemoryMB] int NULL,
    [TotalMemoryGB] decimal(10,2) NULL,
    [NumTempDBFiles] int NULL,
    [MachineType] varchar(20) NULL,
    [WindowsPlatform] varchar(200) NULL,
    [WindowsVersion] varchar(200) NULL,
    [WindowsBuild] varchar(200) NULL,
    [InstanceStartTime] datetime NULL,
    [CollectionTime] datetime NULL,
    [InsertedAt] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [dbo].[ServerInventory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'ServerInventory_CollectorLog')
BEGIN
    CREATE TABLE [dbo].[ServerInventory_CollectorLog] (
    [LogID] int NOT NULL IDENTITY(1,1),
    [ServerName] varchar(200) NULL,
    [ErrorMessage] nvarchar(MAX) NULL,
    [LogTime] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [dbo].[ServerInventory_CollectorLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'SQLServer_Lifecycle')
BEGIN
    CREATE TABLE [dbo].[SQLServer_Lifecycle] (
    [VersionID] int NOT NULL IDENTITY(1,1),
    [MajorVersion] int NOT NULL,
    [VersionName] nvarchar(100) NOT NULL,
    [ReleaseDate] date NULL,
    [MainstreamEndDate] date NULL,
    [ExtendedEndDate] date NULL,
    [ESUYear1EndDate] date NULL,
    [ESUYear2EndDate] date NULL,
    [ESUYear3EndDate] date NULL,
    [Notes] nvarchar(1000) NULL,
    [LastUpdated] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [dbo].[SQLServer_Lifecycle]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'Stg_WaitStats')
BEGIN
    CREATE TABLE [dbo].[Stg_WaitStats] (
    [WaitStatsID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [WaitType] nvarchar(256) NULL,
    [WaitTimeMs] bigint NULL,
    [WaitingTasksCount] bigint NULL,
    [SignalWaitTimeMs] bigint NULL,
    [CollectedAt] datetime2 NULL DEFAULT (sysdatetime()),
    [WaitCategory] nvarchar(256) NULL,
    [WaitSeconds] decimal(18,2) NULL
    );
    PRINT 'Created [dbo].[Stg_WaitStats]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'VeeamBackups_Staging')
BEGIN
    CREATE TABLE [dbo].[VeeamBackups_Staging] (
    [StagingID] int NOT NULL IDENTITY(1,1),
    [JobName] nvarchar(510) NULL,
    [JobType] nvarchar(200) NULL,
    [BackupType] nvarchar(200) NULL,
    [Progress] int NULL,
    [Status] nvarchar(200) NULL,
    [StartTimeRaw] nvarchar(200) NULL,
    [EndTimeRaw] nvarchar(200) NULL,
    [Result] nvarchar(200) NULL,
    [LoadedAt] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [dbo].[VeeamBackups_Staging]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'deployment' AND TABLE_NAME = 'DeploymentBatches')
BEGIN
    CREATE TABLE [deployment].[DeploymentBatches] (
    [DeploymentID] int NOT NULL IDENTITY(1,1),
    [DeploymentDate] datetime2 NULL DEFAULT (sysdatetime()),
    [DeployedBy] nvarchar(256) NULL DEFAULT (suser_sname()),
    [Status] varchar(50) NULL DEFAULT ('Pending'),
    [ComplianceTier] varchar(100) NULL,
    [Notes] nvarchar(MAX) NULL,
    [CompletedDate] datetime2 NULL
    );
    PRINT 'Created [deployment].[DeploymentBatches]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'deployment' AND TABLE_NAME = 'DeploymentHistory')
BEGIN
    CREATE TABLE [deployment].[DeploymentHistory] (
    [HistoryID] int NOT NULL IDENTITY(1,1),
    [DeploymentID] int NOT NULL,
    [ServerName] nvarchar(256) NOT NULL,
    [ActionType] varchar(50) NULL,
    [ObjectName] nvarchar(512) NULL,
    [Status] varchar(50) NULL,
    [ErrorMessage] nvarchar(MAX) NULL,
    [ExecutionDate] datetime2 NULL DEFAULT (sysdatetime()),
    [ExecutedBy] nvarchar(256) NULL DEFAULT (suser_sname())
    );
    PRINT 'Created [deployment].[DeploymentHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'deployment' AND TABLE_NAME = 'ServerDeploymentResults')
BEGIN
    CREATE TABLE [deployment].[ServerDeploymentResults] (
    [ResultID] int NOT NULL IDENTITY(1,1),
    [DeploymentID] int NOT NULL,
    [ServerName] nvarchar(256) NOT NULL,
    [DeploymentDate] datetime2 NULL DEFAULT (sysdatetime()),
    [Status] varchar(50) NULL,
    [LoginsCreated] int NULL,
    [ErrorMessage] nvarchar(MAX) NULL,
    [ExecutionTime] int NULL
    );
    PRINT 'Created [deployment].[ServerDeploymentResults]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'deployment' AND TABLE_NAME = 'ServerDeploymentScripts')
BEGIN
    CREATE TABLE [deployment].[ServerDeploymentScripts] (
    [ScriptID] int NOT NULL IDENTITY(1,1),
    [DeploymentID] int NOT NULL,
    [ServerName] nvarchar(256) NOT NULL,
    [ScriptText] nvarchar(MAX) NOT NULL,
    [Status] varchar(50) NULL DEFAULT ('Ready'),
    [GeneratedDate] datetime2 NULL DEFAULT (sysdatetime()),
    [DeployedDate] datetime2 NULL,
    [DeployedBy] nvarchar(256) NULL,
    [ErrorMessage] nvarchar(MAX) NULL
    );
    PRINT 'Created [deployment].[ServerDeploymentScripts]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dim' AND TABLE_NAME = 'BackupStatus')
BEGIN
    CREATE TABLE [dim].[BackupStatus] (
    [BackupStatusID] int NOT NULL IDENTITY(1,1),
    [StatusName] varchar(50) NOT NULL,
    [Severity] int NULL,
    [CreatedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [dim].[BackupStatus]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dim' AND TABLE_NAME = 'BackupType')
BEGIN
    CREATE TABLE [dim].[BackupType] (
    [BackupTypeKey] int NOT NULL IDENTITY(1,1),
    [BackupTypeCode] varchar(50) NOT NULL,
    [BackupTypeName] varchar(100) NOT NULL,
    [BackupCategory] varchar(50) NULL,
    [IsIncremental] bit NULL DEFAULT ((0)),
    [DefaultSLA_Minutes] int NULL,
    [SortOrder] int NULL DEFAULT ((100)),
    [IsActive] bit NULL DEFAULT ((1))
    );
    PRINT 'Created [dim].[BackupType]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dim' AND TABLE_NAME = 'Calendar')
BEGIN
    CREATE TABLE [dim].[Calendar] (
    [DateKey] int NOT NULL,
    [CalendarDate] date NOT NULL,
    [CalendarYear] int NOT NULL,
    [CalendarQuarter] int NOT NULL,
    [CalendarMonth] int NOT NULL,
    [CalendarDay] int NOT NULL,
    [DayOfWeek] int NOT NULL,
    [DayOfYear] int NOT NULL,
    [WeekOfYear] int NOT NULL,
    [MonthName] varchar(20) NOT NULL,
    [MonthNameShort] char(3) NOT NULL,
    [DayName] varchar(20) NOT NULL,
    [DayNameShort] char(3) NOT NULL,
    [FiscalYear] int NOT NULL,
    [FiscalQuarter] int NOT NULL,
    [FiscalMonth] int NOT NULL,
    [IsWeekend] bit NOT NULL,
    [IsHoliday] bit NOT NULL DEFAULT ((0)),
    [IsBusinessDay] bit NOT NULL
    );
    PRINT 'Created [dim].[Calendar]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dim' AND TABLE_NAME = 'DIM_Server')
BEGIN
    CREATE TABLE [dim].[DIM_Server] (
    [ServerKey] int NOT NULL IDENTITY(1,1),
    [ServerName] sysname NOT NULL,
    [Environment] varchar(50) NULL,
    [Region] varchar(50) NULL,
    [Application] varchar(100) NULL,
    [IsActive] bit NOT NULL DEFAULT ((1)),
    [InsertDate] datetime2 NOT NULL DEFAULT (sysutcdatetime()),
    [UpdateDate] datetime2 NULL
    );
    PRINT 'Created [dim].[DIM_Server]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dim' AND TABLE_NAME = 'DIM_SQLInstance')
BEGIN
    CREATE TABLE [dim].[DIM_SQLInstance] (
    [SQLInstanceKey] int NOT NULL IDENTITY(1,1),
    [ServerKey] int NOT NULL,
    [InstanceName] sysname NOT NULL,
    [Version] varchar(50) NULL,
    [Edition] varchar(50) NULL,
    [IsClustered] bit NULL,
    [IsActive] bit NOT NULL DEFAULT ((1)),
    [InsertDate] datetime2 NOT NULL DEFAULT (sysutcdatetime())
    );
    PRINT 'Created [dim].[DIM_SQLInstance]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dim' AND TABLE_NAME = 'DimDate')
BEGIN
    CREATE TABLE [dim].[DimDate] (
    [DateKey] int NOT NULL,
    [FullDate] date NOT NULL,
    [DayOfWeek] int NULL,
    [DayName] nvarchar(20) NULL,
    [DayOfMonth] int NULL,
    [DayOfYear] int NULL,
    [WeekOfYear] int NULL,
    [MonthNumber] int NULL,
    [MonthName] nvarchar(20) NULL,
    [Quarter] int NULL,
    [Year] int NULL,
    [IsWeekend] bit NULL,
    [IsHoliday] bit NULL DEFAULT ((0))
    );
    PRINT 'Created [dim].[DimDate]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dim' AND TABLE_NAME = 'DimServer')
BEGIN
    CREATE TABLE [dim].[DimServer] (
    [ServerKey] int NOT NULL IDENTITY(1,1),
    [Server] varchar(100) NOT NULL,
    [InstanceName] varchar(100) NULL,
    [FQDN] varchar(255) NULL,
    [Environment] varchar(100) NULL,
    [SqlEdition] varchar(50) NULL,
    [SqlVersionMajor] int NULL,
    [TotalMemoryGB] decimal(10,2) NULL,
    [CpuCount] int NULL,
    [IsCurrent] bit NULL DEFAULT ((1)),
    [EffectiveDate] datetime2 NULL DEFAULT (getdate()),
    [ExpirationDate] datetime2 NULL
    );
    PRINT 'Created [dim].[DimServer]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dim' AND TABLE_NAME = 'DimTime')
BEGIN
    CREATE TABLE [dim].[DimTime] (
    [TimeKey] int NOT NULL,
    [TimeValue] time NOT NULL,
    [Hour] int NULL,
    [Minute] int NULL,
    [HourMinute] nvarchar(10) NULL,
    [AMPM] nvarchar(4) NULL,
    [TimeOfDay] nvarchar(40) NULL
    );
    PRINT 'Created [dim].[DimTime]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dim' AND TABLE_NAME = 'Server')
BEGIN
    CREATE TABLE [dim].[Server] (
    [ServerID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DomainName] nvarchar(256) NULL,
    [Environment] nvarchar(100) NULL,
    [CreatedAt] datetime2 NOT NULL DEFAULT (sysutcdatetime())
    );
    PRINT 'Created [dim].[Server]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dim' AND TABLE_NAME = 'Status')
BEGIN
    CREATE TABLE [dim].[Status] (
    [StatusKey] int NOT NULL IDENTITY(1,1),
    [StatusCode] varchar(50) NOT NULL,
    [StatusName] varchar(100) NOT NULL,
    [Severity] int NOT NULL,
    [DefaultScore] int NULL,
    [DisplayColor] varchar(20) NULL,
    [SortOrder] int NULL DEFAULT ((100))
    );
    PRINT 'Created [dim].[Status]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'drift' AND TABLE_NAME = 'DriftDetectionHistory')
BEGIN
    CREATE TABLE [drift].[DriftDetectionHistory] (
    [DriftDetectionId] int NOT NULL IDENTITY(1,1),
    [SqlInstance] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [BaselineName] nvarchar(256) NOT NULL,
    [ScanTime] datetime2 NOT NULL DEFAULT (getdate()),
    [HasDrift] bit NOT NULL DEFAULT ((0)),
    [DriftSeverity] varchar(20) NOT NULL,
    [DriftCount] int NOT NULL DEFAULT ((0)),
    [AddedCount] int NOT NULL DEFAULT ((0)),
    [ModifiedCount] int NOT NULL DEFAULT ((0)),
    [DeletedCount] int NOT NULL DEFAULT ((0)),
    [SecurityCount] int NOT NULL DEFAULT ((0)),
    [ConfigCount] int NOT NULL DEFAULT ((0))
    );
    PRINT 'Created [drift].[DriftDetectionHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'drift' AND TABLE_NAME = 'DriftItems')
BEGIN
    CREATE TABLE [drift].[DriftItems] (
    [DriftItemId] int NOT NULL IDENTITY(1,1),
    [DriftDetectionId] int NOT NULL,
    [DriftType] varchar(30) NOT NULL,
    [ObjectType] varchar(50) NULL,
    [ObjectName] nvarchar(600) NULL,
    [Severity] varchar(20) NOT NULL,
    [BaselineHash] varchar(64) NULL,
    [CurrentHash] varchar(64) NULL,
    [Details] nvarchar(MAX) NULL,
    [DetectedAt] datetime2 NOT NULL DEFAULT (getdate()),
    [RemediatedAt] datetime2 NULL,
    [RemediatedBy] nvarchar(256) NULL
    );
    PRINT 'Created [drift].[DriftItems]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'drift' AND TABLE_NAME = 'DriftLog')
BEGIN
    CREATE TABLE [drift].[DriftLog] (
    [DriftLogId] int NOT NULL IDENTITY(1,1),
    [LogTime] datetime2 NOT NULL DEFAULT (getdate()),
    [Level] varchar(20) NOT NULL,
    [ServerName] nvarchar(256) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [Message] nvarchar(MAX) NOT NULL
    );
    PRINT 'Created [drift].[DriftLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'drift' AND TABLE_NAME = 'RemediationHistory')
BEGIN
    CREATE TABLE [drift].[RemediationHistory] (
    [RemediationId] int NOT NULL IDENTITY(1,1),
    [DriftDetectionId] int NOT NULL,
    [SqlInstance] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [ScriptPath] nvarchar(1000) NOT NULL,
    [GeneratedAt] datetime2 NOT NULL DEFAULT (getdate()),
    [AppliedAt] datetime2 NULL,
    [AppliedBy] nvarchar(256) NULL,
    [Status] varchar(20) NOT NULL,
    [ItemsRemediated] int NOT NULL DEFAULT ((0))
    );
    PRINT 'Created [drift].[RemediationHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'etl' AND TABLE_NAME = 'dim_ComplianceMetrics')
BEGIN
    CREATE TABLE [etl].[dim_ComplianceMetrics] (
    [MetricID] int NOT NULL IDENTITY(1,1),
    [Framework] varchar(20) NOT NULL,
    [ControlID] varchar(50) NOT NULL,
    [ControlName] nvarchar(1000) NOT NULL,
    [ControlDescription] nvarchar(MAX) NULL,
    [RequiredValue] nvarchar(1000) NULL,
    [CurrentValue] nvarchar(1000) NULL,
    [ComplianceStatus] varchar(20) NOT NULL,
    [CompliancePercentage] decimal(5,2) NULL,
    [LastChecked] datetime2 NOT NULL DEFAULT (getdate()),
    [NextReviewDate] datetime2 NULL,
    [CheckedBy] nvarchar(512) NULL,
    [RemediationRequired] bit NULL DEFAULT ((0)),
    [RemediationPlan] nvarchar(MAX) NULL,
    [RemediationOwner] nvarchar(512) NULL,
    [RemediationDeadline] datetime2 NULL,
    [RemediationStatus] varchar(20) NULL,
    [EvidenceLocation] nvarchar(1000) NULL,
    [EvidenceNotes] nvarchar(MAX) NULL,
    [WaivedBy] nvarchar(512) NULL,
    [WaiverReason] nvarchar(MAX) NULL,
    [WaiverApprovedBy] nvarchar(512) NULL,
    [WaiverExpirationDate] datetime2 NULL
    );
    PRINT 'Created [etl].[dim_ComplianceMetrics]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'etl' AND TABLE_NAME = 'dim_ETL_Servers')
BEGIN
    CREATE TABLE [etl].[dim_ETL_Servers] (
    [ServerID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [HasSSISDB] bit NULL DEFAULT ((0)),
    [SSISFolderCount] int NULL DEFAULT ((0)),
    [SSISProjectCount] int NULL DEFAULT ((0)),
    [SSISPackageCount] int NULL DEFAULT ((0)),
    [HasSSRS] bit NULL DEFAULT ((0)),
    [SSRSReportCount] int NULL DEFAULT ((0)),
    [SSRSActiveSubscriptions] int NULL DEFAULT ((0)),
    [SSRSTotalSubscriptions] int NULL DEFAULT ((0)),
    [ETLJobCount] int NULL DEFAULT ((0)),
    [SSISJobSteps] int NULL,
    [JobNames] nvarchar(MAX) NULL,
    [PowerBIDBCount] int NULL DEFAULT ((0)),
    [PowerBIDatabases] nvarchar(MAX) NULL,
    [HasPowerBI] bit NULL DEFAULT ((0)),
    [LinkedServerCount] int NULL DEFAULT ((0)),
    [LinkedServers] nvarchar(MAX) NULL,
    [IsActive] bit NULL DEFAULT ((1)),
    [Environment] nvarchar(40) NULL DEFAULT ('Production'),
    [LastDiscovered] datetime2 NULL,
    [CreatedDate] datetime2 NULL DEFAULT (getdate()),
    [ModifiedDate] datetime2 NULL DEFAULT (getdate())
    );
    PRINT 'Created [etl].[dim_ETL_Servers]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'etl' AND TABLE_NAME = 'fact_JobExecutionHistory')
BEGIN
    CREATE TABLE [etl].[fact_JobExecutionHistory] (
    [JobHistoryID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [JobID] uniqueidentifier NOT NULL,
    [JobName] nvarchar(512) NOT NULL,
    [JobCategory] nvarchar(256) NULL,
    [RunDate] int NOT NULL,
    [RunTime] int NOT NULL,
    [RunDuration] int NULL,
    [RunDurationMinutes] numeric(18,6) NULL,
    [RunStatus] int NOT NULL,
    [RunStatusText] varchar(11) NOT NULL,
    [StepID] int NULL,
    [StepName] nvarchar(512) NULL,
    [SubSystem] nvarchar(100) NULL,
    [Command] nvarchar(MAX) NULL,
    [Message] nvarchar(MAX) NULL,
    [RunRequestedBy] nvarchar(512) NULL,
    [OperatorEmailed] nvarchar(512) NULL,
    [ContainsPII] bit NULL DEFAULT ((0)),
    [DataClassification] varchar(20) NULL,
    [ComplianceFlag] varchar(20) NULL,
    [ReviewedBy] nvarchar(512) NULL,
    [ReviewedDate] datetime2 NULL,
    [ReviewNotes] nvarchar(MAX) NULL,
    [AuditInsertTime] datetime2 NOT NULL DEFAULT (getdate()),
    [AuditSource] varchar(50) NULL DEFAULT ('PowerShell')
    );
    PRINT 'Created [etl].[fact_JobExecutionHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'etl' AND TABLE_NAME = 'fact_SecurityEvents')
BEGIN
    CREATE TABLE [etl].[fact_SecurityEvents] (
    [EventID] bigint NOT NULL IDENTITY(1,1),
    [EventTime] datetime2 NOT NULL DEFAULT (getdate()),
    [Severity] varchar(20) NOT NULL,
    [EventCategory] varchar(50) NOT NULL,
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NULL,
    [ObjectName] nvarchar(1000) NULL,
    [ObjectType] varchar(50) NULL,
    [UserName] nvarchar(512) NULL,
    [SourceIP] varchar(45) NULL,
    [SourceHostName] nvarchar(256) NULL,
    [UserAction] nvarchar(200) NULL,
    [EventDescription] nvarchar(MAX) NULL,
    [ErrorCode] int NULL,
    [ErrorMessage] nvarchar(MAX) NULL,
    [ResponseRequired] bit NULL DEFAULT ((0)),
    [ResponseDeadline] datetime2 NULL,
    [ResponseTime] datetime2 NULL,
    [RespondedBy] nvarchar(512) NULL,
    [Resolution] nvarchar(MAX) NULL,
    [ResolutionStatus] varchar(20) NULL,
    [ComplianceImpact] varchar(50) NULL,
    [ComplianceViolation] bit NULL DEFAULT ((0)),
    [AlertSent] bit NULL DEFAULT ((0)),
    [AlertRecipients] nvarchar(1000) NULL,
    [AlertSentTime] datetime2 NULL
    );
    PRINT 'Created [etl].[fact_SecurityEvents]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'etl' AND TABLE_NAME = 'fact_SSRS_AccessLog')
BEGIN
    CREATE TABLE [etl].[fact_SSRS_AccessLog] (
    [AccessLogID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [ReportID] uniqueidentifier NOT NULL,
    [ReportPath] nvarchar(2000) NOT NULL,
    [ReportName] nvarchar(1000) NOT NULL,
    [UserName] nvarchar(512) NOT NULL,
    [UserDomain] nvarchar(256) NULL,
    [ClientIP] varchar(45) NULL,
    [ClientUserAgent] nvarchar(1000) NULL,
    [TimeStart] datetime2 NOT NULL,
    [TimeEnd] datetime2 NULL,
    [ExecutionDurationSeconds] int NULL,
    [RequestType] nvarchar(100) NULL,
    [Format] nvarchar(100) NULL,
    [ItemAction] nvarchar(100) NULL,
    [Parameters] nvarchar(MAX) NULL,
    [Status] nvarchar(100) NOT NULL,
    [ByteCount] bigint NULL,
    [RowCount] bigint NULL,
    [TimeDataRetrieval] int NULL,
    [TimeProcessing] int NULL,
    [TimeRendering] int NULL,
    [SubscriptionID] uniqueidentifier NULL,
    [DeliveryMethod] nvarchar(200) NULL,
    [ContainsPII] bit NULL DEFAULT ((0)),
    [PIIPatterns] nvarchar(1000) NULL,
    [DataClassification] varchar(20) NULL,
    [ExportedToPersonalEmail] bit NULL DEFAULT ((0)),
    [ExecutedOffHours] bit NULL DEFAULT ((0)),
    [ReviewRequired] bit NULL DEFAULT ((0)),
    [ReviewedBy] nvarchar(512) NULL,
    [ReviewedDate] datetime2 NULL,
    [ReviewNotes] nvarchar(MAX) NULL,
    [AuditInsertTime] datetime2 NOT NULL DEFAULT (getdate()),
    [AuditSource] varchar(50) NULL DEFAULT ('PowerShell')
    );
    PRINT 'Created [etl].[fact_SSRS_AccessLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'etl' AND TABLE_NAME = 'VeeamBackups')
BEGIN
    CREATE TABLE [etl].[VeeamBackups] (
    [BackupID] int NOT NULL IDENTITY(1,1),
    [JobName] nvarchar(510) NULL,
    [JobType] nvarchar(200) NULL,
    [BackupType] nvarchar(200) NULL,
    [Progress] int NULL,
    [Status] nvarchar(200) NULL,
    [StartTime] datetime2 NULL,
    [EndTime] datetime2 NULL,
    [Result] nvarchar(100) NULL,
    [LoadDate] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [etl].[VeeamBackups]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'etl' AND TABLE_NAME = 'VeeamBackups_Staging')
BEGIN
    CREATE TABLE [etl].[VeeamBackups_Staging] (
    [JobName] nvarchar(510) NULL,
    [JobType] nvarchar(200) NULL,
    [BackupType] nvarchar(200) NULL,
    [Progress] int NULL,
    [Status] nvarchar(200) NULL,
    [StartTimeRaw] nvarchar(100) NULL,
    [EndTimeRaw] nvarchar(100) NULL,
    [Result] nvarchar(100) NULL,
    [LoadDate] datetime2 NULL
    );
    PRINT 'Created [etl].[VeeamBackups_Staging]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'etl' AND TABLE_NAME = 'VeeamBackupStaging')
BEGIN
    CREATE TABLE [etl].[VeeamBackupStaging] (
    [StagingID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(512) NULL,
    [DatabaseName] nvarchar(512) NULL,
    [BackupStartTime] datetime NULL,
    [BackupEndTime] datetime NULL,
    [BackupSizeBytes] bigint NULL,
    [BackupSizeMB] numeric(29,9) NULL,
    [Status] nvarchar(100) NULL,
    [ProcessedDate] datetime NULL,
    [IsProcessed] bit NULL DEFAULT ((0)),
    [LoadDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [etl].[VeeamBackupStaging]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'BackupCompliance')
BEGIN
    CREATE TABLE [fact].[BackupCompliance] (
    [RecordID] int NOT NULL IDENTITY(1,1),
    [ServerName] varchar(200) NULL,
    [DatabaseName] varchar(200) NULL,
    [BackupType] varchar(20) NULL,
    [LastBackupTime] datetime NULL,
    [AgeMinutes] int NULL,
    [SLA_Minutes] int NULL,
    [Status] varchar(20) NULL,
    [InsertTime] datetime2 NULL DEFAULT (sysutcdatetime()),
    [LoadDate] datetime NULL,
    [BackupSource] varchar(100) NULL,
    [VmName] sysname NULL,
    [NextExpectedBackupTime] datetime NULL,
    [JobName] sysname NULL,
    [BackupMode] varchar(50) NULL,
    [BackupSizeGB] decimal(18,2) NULL,
    [Repository] sysname NULL,
    [RepositoryVolume] varchar(100) NULL,
    [RepoTotalTB] decimal(18,2) NULL,
    [RepoFreeTB] decimal(18,2) NULL,
    [ExpectedFrequency] varchar(50) NULL,
    [IsCompliant] bit NULL,
    [SnapshotDate] date NULL,
    [SnapshotHour] tinyint NULL,
    [DateKey] int NULL,
    [ComplianceScore] int NULL,
    [RepoFreePercent] decimal(5,2) NULL,
    [BackupAgeHours] decimal(10,2) NULL
    );
    PRINT 'Created [fact].[BackupCompliance]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'BackupCompliance_Archive')
BEGIN
    CREATE TABLE [fact].[BackupCompliance_Archive] (
    [RecordID] int NOT NULL IDENTITY(1,1),
    [ServerName] varchar(200) NULL,
    [DatabaseName] varchar(200) NULL,
    [BackupType] varchar(20) NULL,
    [LastBackupTime] datetime NULL,
    [AgeMinutes] int NULL,
    [SLA_Minutes] int NULL,
    [Status] varchar(20) NULL,
    [InsertTime] datetime2 NULL,
    [LoadDate] datetime NULL,
    [BackupSource] varchar(100) NULL,
    [VmName] sysname NULL,
    [NextExpectedBackupTime] datetime NULL,
    [JobName] sysname NULL,
    [BackupMode] varchar(50) NULL,
    [BackupSizeGB] decimal(18,2) NULL,
    [Repository] sysname NULL,
    [RepositoryVolume] varchar(100) NULL,
    [RepoTotalTB] decimal(18,2) NULL,
    [RepoFreeTB] decimal(18,2) NULL,
    [ExpectedFrequency] varchar(50) NULL,
    [IsCompliant] bit NULL,
    [SnapshotDate] date NULL,
    [SnapshotHour] tinyint NULL,
    [DateKey] int NULL,
    [ComplianceScore] int NULL,
    [RepoFreePercent] decimal(5,2) NULL,
    [ArchivedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [fact].[BackupCompliance_Archive]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'BackupComplianceLog')
BEGIN
    CREATE TABLE [fact].[BackupComplianceLog] (
    [LogID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [BackupType] varchar(20) NULL,
    [BackupStartDate] datetime NULL,
    [BackupFinishDate] datetime NULL,
    [BackupSizeBytes] bigint NULL,
    [CompressedSizeBytes] bigint NULL,
    [IsCompliant] bit NULL DEFAULT ((1)),
    [ComplianceNotes] nvarchar(1000) NULL,
    [CollectionTime] datetime NULL DEFAULT (getdate()),
    [InsertedAt] datetime NULL DEFAULT (getdate()),
    [Status] varchar(20) NULL DEFAULT ('PASS'),
    [TimeCaptured] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [fact].[BackupComplianceLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'BackupHealth')
BEGIN
    CREATE TABLE [fact].[BackupHealth] (
    [BackupHealthID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [LastBackupTime] datetime2 NULL,
    [LastFullBackup] datetime2 NULL,
    [LastDiffBackup] datetime2 NULL,
    [LastLogBackup] datetime2 NULL,
    [BackupSizeMB] decimal(18,2) NULL,
    [IsCompliant] bit NULL DEFAULT ((1)),
    [SLAHours] int NULL DEFAULT ((24)),
    [LoadDate] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [fact].[BackupHealth]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'BackupHistory')
BEGIN
    CREATE TABLE [fact].[BackupHistory] (
    [ID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [DatabaseName] nvarchar(512) NULL,
    [BackupType] char(1) NULL,
    [BackupFinishTime] datetime2 NULL,
    [HoursSinceLastBackup] decimal(10,2) NULL,
    [CaptureTime] datetime2 NULL DEFAULT (sysdatetime()),
    [JobName] nvarchar(510) NULL,
    [BackupStartTime] datetime2 NULL,
    [DurationSeconds] int NULL,
    [BackupStatus] varchar(50) NULL,
    [RepositoryName] nvarchar(510) NULL,
    [BackupSizeGB] decimal(18,2) NULL,
    [TransferSizeGB] decimal(18,2) NULL,
    [SourceSystem] varchar(50) NOT NULL DEFAULT ('VeeamTaskScheduler'),
    [RawPayload] nvarchar(MAX) NULL,
    [AnomalyScore] decimal(10,6) NULL,
    [BackupMode] varchar(50) NULL,
    [DataSizeGB] decimal(18,2) NULL,
    [RepoFreeTB] decimal(18,2) NULL,
    [RepoTotalTB] decimal(18,2) NULL,
    [RepoFreePercent] decimal(18,2) NULL,
    [RPOHours] int NULL
    );
    PRINT 'Created [fact].[BackupHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'CMSStatusHistory')
BEGIN
    CREATE TABLE [fact].[CMSStatusHistory] (
    [StatusID] bigint NOT NULL IDENTITY(1,1),
    [CaptureDate] date NOT NULL,
    [CMSServerCount] int NOT NULL DEFAULT ((0)),
    [DBAOpsServerCount] int NOT NULL DEFAULT ((0)),
    [MissingFromCMS] int NOT NULL DEFAULT ((0)),
    [MissingFromDBAOps] int NOT NULL DEFAULT ((0)),
    [LinkedServerCount] int NOT NULL DEFAULT ((0)),
    [ProdServers] int NOT NULL DEFAULT ((0)),
    [NonProdServers] int NOT NULL DEFAULT ((0)),
    [SyncStatus] nvarchar(40) NOT NULL DEFAULT ('Unknown'),
    [SyncPercent] decimal(5,2) NOT NULL DEFAULT ((0)),
    [CaptureTime] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [fact].[CMSStatusHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'CPUPerformance')
BEGIN
    CREATE TABLE [fact].[CPUPerformance] (
    [PerformanceID] bigint NOT NULL IDENTITY(1,1),
    [DateKey] int NOT NULL,
    [TimeKey] int NOT NULL,
    [ServerKey] int NOT NULL,
    [CollectionTime] datetime2 NOT NULL,
    [SQLServerCPUPercent] decimal(5,2) NULL,
    [SystemIdleCPUPercent] decimal(5,2) NULL,
    [OtherProcessCPUPercent] decimal(5,2) NULL,
    [SignalWaitPercent] decimal(5,2) NULL
    );
    PRINT 'Created [fact].[CPUPerformance]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'DailyComplianceSummary')
BEGIN
    CREATE TABLE [fact].[DailyComplianceSummary] (
    [SummaryID] int NOT NULL IDENTITY(1,1),
    [SummaryDate] date NOT NULL,
    [DateKey] int NULL,
    [TotalServers] int NOT NULL DEFAULT ((0)),
    [CompliantServers] int NOT NULL DEFAULT ((0)),
    [NonCompliantServers] int NOT NULL DEFAULT ((0)),
    [UnknownServers] int NOT NULL DEFAULT ((0)),
    [CompliancePercent] decimal(5,2) NULL,
    [AvgComplianceScore] decimal(5,2) NULL,
    [MinComplianceScore] int NULL,
    [MaxComplianceScore] int NULL,
    [SuccessCount] int NULL DEFAULT ((0)),
    [WarningCount] int NULL DEFAULT ((0)),
    [StaleCount] int NULL DEFAULT ((0)),
    [CriticalCount] int NULL DEFAULT ((0)),
    [FailedCount] int NULL DEFAULT ((0)),
    [MissingCount] int NULL DEFAULT ((0)),
    [AvgRepoFreePercent] decimal(5,2) NULL,
    [ReposBelow20Percent] int NULL DEFAULT ((0)),
    [ReposBelow10Percent] int NULL DEFAULT ((0)),
    [AnomaliesDetected] int NULL DEFAULT ((0)),
    [HighSeverityAnomalies] int NULL DEFAULT ((0)),
    [GeneratedDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [fact].[DailyComplianceSummary]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'DatabaseStatus')
BEGIN
    CREATE TABLE [fact].[DatabaseStatus] (
    [StatusID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(512) NOT NULL,
    [DatabaseName] nvarchar(512) NOT NULL,
    [DatabaseState] nvarchar(100) NULL,
    [RecoveryModel] nvarchar(100) NULL,
    [CompatibilityLevel] int NULL,
    [DataSizeMB] decimal(18,2) NULL,
    [LogSizeMB] decimal(18,2) NULL,
    [DataUsedMB] decimal(18,2) NULL,
    [LogUsedMB] decimal(18,2) NULL,
    [LastFullBackup] datetime NULL,
    [LastDiffBackup] datetime NULL,
    [LastLogBackup] datetime NULL,
    [UserCount] int NULL,
    [CollectedDate] datetime NULL DEFAULT (getdate()),
    [SnapshotDate] datetime NULL
    );
    PRINT 'Created [fact].[DatabaseStatus]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'DiskSpaceMetrics')
BEGIN
    CREATE TABLE [fact].[DiskSpaceMetrics] (
    [MetricID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DriveLetter] nvarchar(100) NULL,
    [VolumeLabel] nvarchar(200) NULL,
    [TotalSpaceGB] decimal(10,2) NULL,
    [FreeSpaceGB] decimal(10,2) NULL,
    [FreePercent] decimal(5,2) NULL,
    [CaptureDate] datetime NOT NULL DEFAULT (getdate())
    );
    PRINT 'Created [fact].[DiskSpaceMetrics]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'HealthCheckDetails')
BEGIN
    CREATE TABLE [fact].[HealthCheckDetails] (
    [DetailID] int NOT NULL IDENTITY(1,1),
    [RunID] uniqueidentifier NOT NULL,
    [Category] varchar(50) NOT NULL,
    [Severity] varchar(20) NOT NULL DEFAULT ('INFO'),
    [Message] nvarchar(MAX) NOT NULL,
    [LoggedOn] datetime2 NOT NULL DEFAULT (sysutcdatetime())
    );
    PRINT 'Created [fact].[HealthCheckDetails]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'HealthCheckSummary')
BEGIN
    CREATE TABLE [fact].[HealthCheckSummary] (
    [SummaryID] int NOT NULL IDENTITY(1,1),
    [RunID] uniqueidentifier NOT NULL,
    [RunTime] datetime2 NOT NULL,
    [ServerName] nvarchar(256) NOT NULL,
    [OverallStatus] varchar(20) NOT NULL,
    [CpuLoadPercent] decimal(5,2) NULL,
    [MemoryLoadPercent] decimal(5,2) NULL,
    [BlockingCount] int NULL,
    [WaitCategory] varchar(100) NULL,
    [Notes] nvarchar(MAX) NULL,
    [CreatedOn] datetime2 NOT NULL DEFAULT (sysutcdatetime())
    );
    PRINT 'Created [fact].[HealthCheckSummary]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'JobComplianceLog')
BEGIN
    CREATE TABLE [fact].[JobComplianceLog] (
    [LogID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [JobName] nvarchar(512) NOT NULL,
    [JobEnabled] bit NULL,
    [LastRunDate] datetime NULL,
    [LastRunOutcome] nvarchar(100) NULL,
    [NextRunDate] datetime NULL,
    [ScheduleEnabled] bit NULL,
    [IsCompliant] bit NULL,
    [ComplianceIssue] nvarchar(1000) NULL,
    [CaptureTime] datetime NOT NULL DEFAULT (getdate()),
    [Status] varchar(20) NULL DEFAULT ('PASS'),
    [TimeCaptured] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [fact].[JobComplianceLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'LoginStatus')
BEGIN
    CREATE TABLE [fact].[LoginStatus] (
    [LogID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [LoginName] nvarchar(512) NULL,
    [LoginType] varchar(50) NULL,
    [IsDisabled] bit NULL,
    [IsLocked] bit NULL,
    [PasswordExpired] bit NULL,
    [DaysUntilExpiration] int NULL,
    [Status] varchar(20) NULL DEFAULT ('PASS'),
    [TimeCaptured] datetime NULL DEFAULT (getdate()),
    [Notes] nvarchar(1000) NULL,
    [InsertedAt] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [fact].[LoginStatus]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'MemoryCompliance')
BEGIN
    CREATE TABLE [fact].[MemoryCompliance] (
    [ID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [TimeCaptured] datetime2 NOT NULL
    );
    PRINT 'Created [fact].[MemoryCompliance]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'MemoryPerformance')
BEGIN
    CREATE TABLE [fact].[MemoryPerformance] (
    [PerformanceID] bigint NOT NULL IDENTITY(1,1),
    [DateKey] int NOT NULL,
    [TimeKey] int NOT NULL,
    [ServerKey] int NOT NULL,
    [CollectionTime] datetime2 NOT NULL,
    [TotalServerMemoryMB] decimal(18,2) NULL,
    [TargetServerMemoryMB] decimal(18,2) NULL,
    [MemoryUtilizationPercent] decimal(5,2) NULL,
    [PageLifeExpectancy] int NULL,
    [BufferCacheHitRatio] decimal(5,2) NULL
    );
    PRINT 'Created [fact].[MemoryPerformance]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'PerformanceMetrics')
BEGIN
    CREATE TABLE [fact].[PerformanceMetrics] (
    [MetricID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [MetricName] nvarchar(256) NULL,
    [MetricValue] decimal(18,4) NULL,
    [MetricUnit] nvarchar(100) NULL,
    [CollectedAt] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [fact].[PerformanceMetrics]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'ReplicationHealth')
BEGIN
    CREATE TABLE [fact].[ReplicationHealth] (
    [ReplicationHealthID] bigint NOT NULL IDENTITY(1,1),
    [PublisherName] nvarchar(256) NOT NULL,
    [PublisherDB] nvarchar(256) NULL,
    [PublicationName] nvarchar(256) NOT NULL,
    [SubscriberName] nvarchar(256) NULL,
    [SubscriberDB] nvarchar(256) NULL,
    [LatencySeconds] int NULL,
    [PendingCommands] int NULL,
    [Status] nvarchar(100) NULL,
    [LastSyncTime] datetime NULL,
    [CollectionTime] datetime NOT NULL DEFAULT (getdate())
    );
    PRINT 'Created [fact].[ReplicationHealth]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'ReplicationHealthHistory')
BEGIN
    CREATE TABLE [fact].[ReplicationHealthHistory] (
    [HistoryID] int NOT NULL IDENTITY(1,1),
    [ReplicationID] int NULL,
    [PublisherServer] nvarchar(256) NOT NULL,
    [SubscriberServer] nvarchar(256) NULL,
    [LatencySeconds] int NULL,
    [PendingCommands] bigint NULL,
    [Status] nvarchar(100) NULL,
    [CollectionTime] datetime2 NULL DEFAULT (getdate()),
    [LoadDate] datetime2 NULL DEFAULT (getdate())
    );
    PRINT 'Created [fact].[ReplicationHealthHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'ReplicationLatency')
BEGIN
    CREATE TABLE [fact].[ReplicationLatency] (
    [LatencyID] bigint NOT NULL IDENTITY(1,1),
    [PublisherServer] nvarchar(512) NOT NULL,
    [PublicationName] nvarchar(512) NOT NULL,
    [SubscriberServer] nvarchar(512) NOT NULL,
    [LatencySeconds] int NULL,
    [PendingCommands] int NULL,
    [Status] nvarchar(100) NULL,
    [CollectedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [fact].[ReplicationLatency]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'ReplicationMetricsHistory')
BEGIN
    CREATE TABLE [fact].[ReplicationMetricsHistory] (
    [HistoryID] int NOT NULL IDENTITY(1,1),
    [PublisherServer] nvarchar(256) NOT NULL,
    [PublisherDatabase] nvarchar(256) NULL,
    [PublicationName] nvarchar(512) NULL,
    [SubscriberServer] nvarchar(256) NULL,
    [SubscriberDatabase] nvarchar(256) NULL,
    [PendingCmdCount] bigint NULL,
    [LatencySeconds] int NULL,
    [DeliveryRate] float NULL,
    [Status] nvarchar(100) NULL,
    [CollectionTime] datetime2 NOT NULL,
    [LoadDate] datetime2 NULL DEFAULT (getdate())
    );
    PRINT 'Created [fact].[ReplicationMetricsHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'ServerConfigCompliance')
BEGIN
    CREATE TABLE [fact].[ServerConfigCompliance] (
    [ConfigID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [CaptureTime] datetime NOT NULL DEFAULT (getdate()),
    [MAXDOP] int NULL,
    [CostThresholdForParallelism] int NULL,
    [MaxServerMemoryMB] int NULL,
    [MinServerMemoryMB] int NULL,
    [OptimizeForAdHocWorkloads] bit NULL,
    [MaxDegreeOfParallelism] int NULL,
    [LogicalCPUCount] int NULL,
    [PhysicalCPUCount] int NULL,
    [NumaNodeCount] int NULL,
    [MAXDOPCompliant] bit NULL,
    [CostThresholdCompliant] bit NULL,
    [MemoryCompliant] bit NULL,
    [OverallCompliant] bit NULL
    );
    PRINT 'Created [fact].[ServerConfigCompliance]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'ServerHealth')
BEGIN
    CREATE TABLE [fact].[ServerHealth] (
    [ServerHealthID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [CPUPercent] decimal(5,2) NULL,
    [MemoryPercent] decimal(5,2) NULL,
    [TimeCaptured] datetime NULL
    );
    PRINT 'Created [fact].[ServerHealth]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'ServerInventoryHistory')
BEGIN
    CREATE TABLE [fact].[ServerInventoryHistory] (
    [HistoryID] int NOT NULL IDENTITY(1,1),
    [ServerName] varchar(128) NULL,
    [SQLVersion] varchar(50) NULL,
    [CPUCount] int NULL,
    [TotalMemoryMB] int NULL,
    [MaxMemoryMB] int NULL,
    [MaxDOP] int NULL,
    [CostThreshold] int NULL,
    [SnapshotDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [fact].[ServerInventoryHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'ServiceStatus')
BEGIN
    CREATE TABLE [fact].[ServiceStatus] (
    [LogID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [ServiceName] nvarchar(512) NULL,
    [ServiceDisplayName] nvarchar(512) NULL,
    [ServiceState] varchar(50) NULL,
    [StartMode] varchar(50) NULL,
    [ServiceAccount] nvarchar(512) NULL,
    [Status] varchar(20) NULL DEFAULT ('PASS'),
    [TimeCaptured] datetime NULL DEFAULT (getdate()),
    [Notes] nvarchar(1000) NULL,
    [InsertedAt] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [fact].[ServiceStatus]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'fact' AND TABLE_NAME = 'WaitStats')
BEGIN
    CREATE TABLE [fact].[WaitStats] (
    [WaitStatsID] int NOT NULL IDENTITY(1,1),
    [ServerName] sysname NOT NULL,
    [WaitType] nvarchar(400) NOT NULL,
    [WaitTimeMs] bigint NULL,
    [WaitCount] bigint NULL,
    [SignalWaitTimeMs] bigint NULL,
    [CaptureTime] datetime2 NOT NULL DEFAULT (sysutcdatetime())
    );
    PRINT 'Created [fact].[WaitStats]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'FrameworkHealth' AND TABLE_NAME = 'HealthCheckResults')
BEGIN
    CREATE TABLE [FrameworkHealth].[HealthCheckResults] (
    [ResultID] bigint NOT NULL IDENTITY(1,1),
    [CheckTime] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [CheckCategory] nvarchar(100) NOT NULL,
    [ObjectName] nvarchar(512) NOT NULL,
    [Status] nvarchar(40) NOT NULL,
    [CurrentValue] nvarchar(1000) NULL,
    [ExpectedValue] nvarchar(1000) NULL,
    [Message] nvarchar(MAX) NULL,
    [LastDataTime] datetime2 NULL,
    [RowCount] bigint NULL,
    [AgeMinutes] int NULL
    );
    PRINT 'Created [FrameworkHealth].[HealthCheckResults]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'FrameworkHealth' AND TABLE_NAME = 'HealthSummary')
BEGIN
    CREATE TABLE [FrameworkHealth].[HealthSummary] (
    [SummaryID] int NOT NULL IDENTITY(1,1),
    [CheckTime] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [TotalChecks] int NOT NULL,
    [OKCount] int NOT NULL,
    [WarningCount] int NOT NULL,
    [CriticalCount] int NOT NULL,
    [ErrorCount] int NOT NULL,
    [HealthScore] decimal(5,2) NULL,
    [TablesHealthy] int NULL,
    [TablesStale] int NULL,
    [JobsHealthy] int NULL,
    [JobsFailed] int NULL,
    [ServersReachable] int NULL,
    [ServersUnreachable] int NULL,
    [NotificationSent] bit NULL DEFAULT ((0))
    );
    PRINT 'Created [FrameworkHealth].[HealthSummary]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'FrameworkHealth' AND TABLE_NAME = 'ServerHealthStatus')
BEGIN
    CREATE TABLE [FrameworkHealth].[ServerHealthStatus] (
    [StatusID] bigint NOT NULL IDENTITY(1,1),
    [CheckTime] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [ServerName] nvarchar(256) NOT NULL,
    [IsReachable] bit NULL,
    [LastSuccessfulCollection] datetime2 NULL,
    [CollectionAgeMinutes] int NULL,
    [TablesWithData] int NULL,
    [Status] nvarchar(40) NOT NULL,
    [ErrorMessage] nvarchar(MAX) NULL
    );
    PRINT 'Created [FrameworkHealth].[ServerHealthStatus]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'FrameworkHealth' AND TABLE_NAME = 'TableRegistry')
BEGIN
    CREATE TABLE [FrameworkHealth].[TableRegistry] (
    [RegistryID] int NOT NULL IDENTITY(1,1),
    [SchemaName] nvarchar(256) NOT NULL,
    [TableName] nvarchar(256) NOT NULL,
    [Category] nvarchar(100) NOT NULL,
    [ExpectedRefreshMinutes] int NULL,
    [MinimumRowCount] int NULL DEFAULT ((0)),
    [DateColumn] nvarchar(256) NULL,
    [IsActive] bit NULL DEFAULT ((1)),
    [CollectorJobName] nvarchar(512) NULL,
    [CollectorProcedure] nvarchar(512) NULL,
    [Description] nvarchar(1000) NULL,
    [CreatedDate] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [FrameworkHealth].[TableRegistry]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'hadr' AND TABLE_NAME = 'AGDatabases')
BEGIN
    CREATE TABLE [hadr].[AGDatabases] (
    [AGDatabaseID] int NOT NULL IDENTITY(1,1),
    [AGID] int NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [IsLocalDatabase] bit NOT NULL,
    [IsPrimaryReplica] bit NOT NULL,
    [SynchronizationState] tinyint NULL,
    [SynchronizationHealth] tinyint NULL,
    [DatabaseState] tinyint NULL,
    [IsSuspended] bit NULL,
    [SuspendReason] tinyint NULL,
    [CollectedDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [hadr].[AGDatabases]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'hadr' AND TABLE_NAME = 'AGPerformanceMetrics')
BEGIN
    CREATE TABLE [hadr].[AGPerformanceMetrics] (
    [MetricID] bigint NOT NULL IDENTITY(1,1),
    [AGID] int NOT NULL,
    [ReplicaServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [LogSendQueueSizeKB] bigint NULL,
    [LogSendRateKB] bigint NULL,
    [RedoQueueSizeKB] bigint NULL,
    [RedoRateKB] bigint NULL,
    [EstimatedDataLossSeconds] int NULL,
    [EstimatedRecoveryTimeSeconds] int NULL,
    [SecondaryLagSeconds] int NULL,
    [LastCommitTime] datetime NULL,
    [CollectedDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [hadr].[AGPerformanceMetrics]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'hadr' AND TABLE_NAME = 'AGReplicas')
BEGIN
    CREATE TABLE [hadr].[AGReplicas] (
    [ReplicaID] int NOT NULL IDENTITY(1,1),
    [AGID] int NOT NULL,
    [ReplicaServerName] nvarchar(256) NOT NULL,
    [AvailabilityMode] tinyint NOT NULL,
    [FailoverMode] tinyint NOT NULL,
    [SessionTimeout] int NULL,
    [PrimaryRoleAllowConnections] tinyint NULL,
    [SecondaryRoleAllowConnections] tinyint NULL,
    [CreateDate] datetime NULL,
    [ModifyDate] datetime NULL,
    [BackupPriority] int NULL,
    [ReadOnlyRoutingURL] nvarchar(512) NULL,
    [CollectedDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [hadr].[AGReplicas]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'hadr' AND TABLE_NAME = 'AvailabilityGroups')
BEGIN
    CREATE TABLE [hadr].[AvailabilityGroups] (
    [AGID] int NOT NULL IDENTITY(1,1),
    [ServerID] int NOT NULL,
    [AGName] nvarchar(256) NOT NULL,
    [PrimaryServerName] nvarchar(256) NULL,
    [AutomatedBackupPreference] nvarchar(120) NULL,
    [FailureConditionLevel] int NULL,
    [HealthCheckTimeout] int NULL,
    [IsDistributedAG] bit NOT NULL DEFAULT ((0)),
    [CollectedDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [hadr].[AvailabilityGroups]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'hadr' AND TABLE_NAME = 'FailoverClusterInstances')
BEGIN
    CREATE TABLE [hadr].[FailoverClusterInstances] (
    [FCIID] int NOT NULL IDENTITY(1,1),
    [ServerID] int NOT NULL,
    [ClusterName] nvarchar(256) NOT NULL,
    [NodeName] nvarchar(256) NOT NULL,
    [IsCurrentOwner] bit NOT NULL,
    [QuorumType] tinyint NULL,
    [QuorumState] tinyint NULL,
    [CollectedDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [hadr].[FailoverClusterInstances]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'hadr' AND TABLE_NAME = 'FCIResources')
BEGIN
    CREATE TABLE [hadr].[FCIResources] (
    [ResourceID] int NOT NULL IDENTITY(1,1),
    [FCIID] int NOT NULL,
    [ResourceName] nvarchar(256) NOT NULL,
    [ResourceType] nvarchar(120) NOT NULL,
    [ResourceState] tinyint NULL,
    [OwnerNode] nvarchar(256) NULL,
    [CollectedDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [hadr].[FCIResources]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'health' AND TABLE_NAME = 'ServerHealth')
BEGIN
    CREATE TABLE [health].[ServerHealth] (
    [HealthID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(510) NOT NULL,
    [CollectedAt] datetime NOT NULL,
    [IsOnline] bit NULL,
    [SQLServerStatus] nvarchar(100) NULL,
    [SQLVersion] nvarchar(1000) NULL,
    [CPUUsagePercent] decimal(5,2) NULL,
    [MemoryUsedMB] bigint NULL,
    [MemoryTotalMB] bigint NULL,
    [MemoryUsedPercent] decimal(5,2) NULL,
    [DataDriveFreeGB] decimal(18,2) NULL,
    [DataDriveTotalGB] decimal(18,2) NULL,
    [DataDriveFreePercent] decimal(5,2) NULL,
    [LogDriveFreeGB] decimal(18,2) NULL,
    [LogDriveTotalGB] decimal(18,2) NULL,
    [LogDriveFreePercent] decimal(5,2) NULL,
    [TotalDatabases] int NULL,
    [OnlineDatabases] int NULL,
    [OfflineDatabases] int NULL,
    [SuspectDatabases] int NULL,
    [RecoveringDatabases] int NULL,
    [ErrorMessage] nvarchar(MAX) NULL
    );
    PRINT 'Created [health].[ServerHealth]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'inventory' AND TABLE_NAME = 'ApplicationMapping')
BEGIN
    CREATE TABLE [inventory].[ApplicationMapping] (
    [AppID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [ApplicationName] nvarchar(512) NULL,
    [LoginName] nvarchar(256) NULL,
    [HostName] nvarchar(256) NULL,
    [ConnectionCount] int NULL,
    [LastSeen] datetime2 NULL,
    [CollectedAt] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [inventory].[ApplicationMapping]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'inventory' AND TABLE_NAME = 'DatabaseChangeLog')
BEGIN
    CREATE TABLE [inventory].[DatabaseChangeLog] (
    [ChangeLogID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [ChangeType] nvarchar(100) NOT NULL,
    [OldValue] nvarchar(MAX) NULL,
    [NewValue] nvarchar(MAX) NULL,
    [OldOwner] nvarchar(256) NULL,
    [NewOwner] nvarchar(256) NULL,
    [Creator] nvarchar(256) NULL,
    [ChangeDetectedAt] datetime NOT NULL DEFAULT (getdate()),
    [DatabaseCreateDate] datetime NULL,
    [NotificationSent] bit NOT NULL DEFAULT ((0)),
    [NotificationSentAt] datetime NULL,
    [Notes] nvarchar(MAX) NULL
    );
    PRINT 'Created [inventory].[DatabaseChangeLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'inventory' AND TABLE_NAME = 'DatabaseDetails')
BEGIN
    CREATE TABLE [inventory].[DatabaseDetails] (
    [DetailID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [DatabaseID] int NULL,
    [CreateDate] datetime NULL,
    [CompatibilityLevel] int NULL,
    [RecoveryModel] nvarchar(120) NULL,
    [StateDesc] nvarchar(120) NULL,
    [CollationName] nvarchar(256) NULL,
    [IsAutoCloseOn] bit NULL,
    [IsAutoShrinkOn] bit NULL,
    [IsReadOnly] bit NULL,
    [IsEncrypted] bit NULL,
    [PageVerifyOption] nvarchar(120) NULL,
    [LogReuseWaitDesc] nvarchar(120) NULL,
    [OwnerName] nvarchar(256) NULL,
    [DataFileSizeMB] decimal(18,2) NULL,
    [LogFileSizeMB] decimal(18,2) NULL,
    [TotalSizeMB] decimal(18,2) NULL,
    [CollectedAt] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [inventory].[DatabaseDetails]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'inventory' AND TABLE_NAME = 'DatabaseInventorySnapshot')
BEGIN
    CREATE TABLE [inventory].[DatabaseInventorySnapshot] (
    [SnapshotID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [DatabaseID] int NULL,
    [OwnerName] nvarchar(256) NULL,
    [CreateDate] datetime NULL,
    [StateDesc] nvarchar(120) NULL,
    [RecoveryModelDesc] nvarchar(120) NULL,
    [CompatibilityLevel] int NULL,
    [CollationName] nvarchar(256) NULL,
    [SnapshotDate] datetime NOT NULL DEFAULT (getdate())
    );
    PRINT 'Created [inventory].[DatabaseInventorySnapshot]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'inventory' AND TABLE_NAME = 'DatabaseOwnership')
BEGIN
    CREATE TABLE [inventory].[DatabaseOwnership] (
    [OwnershipID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [TechnicalOwner] nvarchar(256) NULL,
    [BusinessOwner] nvarchar(256) NULL,
    [SupportTeam] nvarchar(400) NULL,
    [Purpose] nvarchar(1000) NULL,
    [DataClassification] nvarchar(100) NULL,
    [CreatedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [inventory].[DatabaseOwnership]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'inventory' AND TABLE_NAME = 'DatabaseSettingsHistory')
BEGIN
    CREATE TABLE [inventory].[DatabaseSettingsHistory] (
    [SettingHistoryID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [SettingName] nvarchar(256) NOT NULL,
    [OldValue] nvarchar(1000) NULL,
    [NewValue] nvarchar(1000) NULL,
    [ChangedAt] datetime2 NOT NULL,
    [ChangedBy] nvarchar(256) NULL
    );
    PRINT 'Created [inventory].[DatabaseSettingsHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'inventory' AND TABLE_NAME = 'dim_ServerBuilds')
BEGIN
    CREATE TABLE [inventory].[dim_ServerBuilds] (
    [ServerName] nvarchar(256) NOT NULL,
    [ProductVersion] nvarchar(100) NOT NULL,
    [ProductLevel] nvarchar(100) NULL,
    [ProductUpdateLevel] nvarchar(100) NULL,
    [CurrentVersion] nvarchar(100) NOT NULL,
    [CurrentBuild] nvarchar(100) NOT NULL,
    [CurrentSPLevel] int NULL,
    [CurrentCULevel] int NULL,
    [LatestAvailableVersion] nvarchar(100) NULL,
    [LatestAvailableBuild] nvarchar(100) NULL,
    [LatestAvailableCU] int NULL,
    [BuildsBehind] int NULL,
    [SecurityPatchesAvailable] int NULL DEFAULT ((0)),
    [LastChecked] datetime2 NOT NULL DEFAULT (getdate()),
    [LastUpdated] datetime2 NOT NULL DEFAULT (getdate()),
    [MajorVersionEOL] date NULL,
    [ExtendedSupportEOL] date NULL,
    [CVEsAddressed] nvarchar(MAX) NULL,
    [UpdateRecommendation] nvarchar(1000) NULL,
    [UpdatePriority] int NULL,
    [KBArticles] nvarchar(MAX) NULL,
    [DownloadURL] nvarchar(2000) NULL,
    [ReleaseDate] date NULL,
    [IsSupported] bit NOT NULL DEFAULT ((1)),
    [DaysTilEOL] int NULL
    );
    PRINT 'Created [inventory].[dim_ServerBuilds]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'inventory' AND TABLE_NAME = 'FileGrowthConfig')
BEGIN
    CREATE TABLE [inventory].[FileGrowthConfig] (
    [ConfigID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [FileName] nvarchar(256) NULL,
    [FileType] nvarchar(20) NULL,
    [PhysicalPath] nvarchar(1024) NULL,
    [SizeMB] decimal(18,2) NULL,
    [MaxSizeMB] decimal(18,2) NULL,
    [GrowthValue] int NULL,
    [IsPercentGrowth] bit NULL,
    [GrowthMB] decimal(18,2) NULL,
    [GrowthDescription] nvarchar(200) NULL,
    [IsCompliant] bit NULL,
    [ComplianceNote] nvarchar(512) NULL,
    [CollectedAt] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [inventory].[FileGrowthConfig]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'inventory' AND TABLE_NAME = 'Linked_Servers')
BEGIN
    CREATE TABLE [inventory].[Linked_Servers] (
    [ServerName] varchar(60) NOT NULL,
    [RmtServer] varchar(60) NOT NULL,
    [SrvProduct] varchar(60) NOT NULL,
    [provider] varchar(60) NOT NULL,
    [Data_Source] varchar(100) NOT NULL,
    [catalog] varchar(60) NULL,
    [rmtusername] varchar(60) NULL,
    [uses_self_credential] bit NULL,
    [Remote_Login] varchar(60) NOT NULL,
    [Created] datetime NULL,
    [Modified] datetime NULL
    );
    PRINT 'Created [inventory].[Linked_Servers]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'inventory' AND TABLE_NAME = 'Linked_Servers_Load')
BEGIN
    CREATE TABLE [inventory].[Linked_Servers_Load] (
    [ServerName] varchar(60) NOT NULL,
    [RmtServer] varchar(60) NOT NULL,
    [SrvProduct] varchar(60) NOT NULL,
    [provider] varchar(60) NOT NULL,
    [Data_Source] varchar(100) NOT NULL,
    [catalog] varchar(60) NULL,
    [rmtusername] varchar(60) NULL,
    [uses_self_credential] bit NULL,
    [Remote_Login] varchar(60) NOT NULL
    );
    PRINT 'Created [inventory].[Linked_Servers_Load]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'inventory' AND TABLE_NAME = 'LinkedServerHealth')
BEGIN
    CREATE TABLE [inventory].[LinkedServerHealth] (
    [HealthID] bigint NOT NULL IDENTITY(1,1),
    [SourceServer] nvarchar(256) NOT NULL,
    [LinkedServerName] nvarchar(256) NOT NULL,
    [IsConnectable] bit NULL,
    [ResponseTimeMs] int NULL,
    [LastError] nvarchar(MAX) NULL,
    [TestedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [inventory].[LinkedServerHealth]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'inventory' AND TABLE_NAME = 'MonitoredServers')
BEGIN
    CREATE TABLE [inventory].[MonitoredServers] (
    [ServerID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(512) NOT NULL,
    [LinkedServerName] nvarchar(512) NULL,
    [IsActive] bit NOT NULL DEFAULT ((1)),
    [LastChecked] datetime NULL,
    [LastSuccessful] datetime NULL,
    [ErrorMessage] nvarchar(MAX) NULL,
    [AddedDate] datetime NOT NULL DEFAULT (getdate()),
    [AddedBy] nvarchar(512) NULL DEFAULT (suser_sname())
    );
    PRINT 'Created [inventory].[MonitoredServers]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'inventory' AND TABLE_NAME = 'ServerClassification')
BEGIN
    CREATE TABLE [inventory].[ServerClassification] (
    [ClassificationID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [Environment] nvarchar(100) NULL,
    [Tier] nvarchar(40) NULL,
    [Criticality] nvarchar(40) NULL,
    [DataCenter] nvarchar(200) NULL,
    [BusinessUnit] nvarchar(400) NULL,
    [PrimaryContact] nvarchar(256) NULL,
    [MaintenanceWindow] nvarchar(200) NULL,
    [PatchGroup] nvarchar(100) NULL,
    [LastUpdated] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [inventory].[ServerClassification]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'jobs' AND TABLE_NAME = 'JobRunHistory')
BEGIN
    CREATE TABLE [jobs].[JobRunHistory] (
    [HistoryID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [JobID] uniqueidentifier NULL,
    [JobName] nvarchar(510) NOT NULL,
    [StepID] int NULL,
    [StepName] nvarchar(256) NULL,
    [RunDate] datetime NOT NULL,
    [RunDuration_Seconds] int NULL,
    [RunOutcome] nvarchar(40) NULL,
    [Message] nvarchar(MAX) NULL,
    [RetriesAttempted] int NULL,
    [CollectedDate] datetime2 NULL DEFAULT (getdate())
    );
    PRINT 'Created [jobs].[JobRunHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'jobs' AND TABLE_NAME = 'SQLAgentJobs')
BEGIN
    CREATE TABLE [jobs].[SQLAgentJobs] (
    [JobID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [JobName] nvarchar(512) NOT NULL,
    [JobCategory] nvarchar(256) NULL,
    [JobDescription] nvarchar(MAX) NULL,
    [IsEnabled] bit NULL,
    [DateCreated] datetime NULL,
    [DateModified] datetime NULL,
    [LastRunDate] datetime NULL,
    [LastRunOutcome] nvarchar(100) NULL,
    [LastRunDuration_Seconds] int NULL,
    [LastRunMessage] nvarchar(MAX) NULL,
    [NextRunDate] datetime NULL,
    [OwnerName] nvarchar(256) NULL,
    [ScheduleCount] int NULL,
    [StepCount] int NULL,
    [CollectedAt] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [jobs].[SQLAgentJobs]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'kb' AND TABLE_NAME = 'dim_Articles')
BEGIN
    CREATE TABLE [kb].[dim_Articles] (
    [ArticleID] int NOT NULL IDENTITY(1,1),
    [Title] nvarchar(1000) NOT NULL,
    [Category] nvarchar(200) NOT NULL,
    [SubCategory] nvarchar(200) NULL,
    [ErrorPattern] nvarchar(1000) NULL,
    [ErrorNumber] int NULL,
    [Symptoms] nvarchar(MAX) NOT NULL,
    [RootCause] nvarchar(MAX) NULL,
    [Solution] nvarchar(MAX) NOT NULL,
    [PreventionSteps] nvarchar(MAX) NULL,
    [RelatedCVEs] nvarchar(1000) NULL,
    [RelatedKBs] nvarchar(1000) NULL,
    [CreatedBy] nvarchar(200) NOT NULL,
    [CreatedDate] datetime2 NOT NULL DEFAULT (getdate()),
    [LastModifiedBy] nvarchar(200) NULL,
    [LastModified] datetime2 NULL,
    [LastUsed] datetime2 NULL,
    [UseCount] int NOT NULL DEFAULT ((0)),
    [HelpfulCount] int NOT NULL DEFAULT ((0)),
    [NotHelpfulCount] int NOT NULL DEFAULT ((0)),
    [HelpfulRatio] decimal(20,13) NULL,
    [Source] nvarchar(400) NOT NULL DEFAULT ('Internal'),
    [SourceURL] nvarchar(2000) NULL,
    [IsVerified] bit NOT NULL DEFAULT ((0)),
    [VerifiedBy] nvarchar(200) NULL,
    [VerifiedDate] datetime2 NULL,
    [Tags] nvarchar(1000) NULL
    );
    PRINT 'Created [kb].[dim_Articles]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'log' AND TABLE_NAME = 'AutomationLog')
BEGIN
    CREATE TABLE [log].[AutomationLog] (
    [LogID] int NOT NULL IDENTITY(1,1),
    [ModuleName] nvarchar(256) NOT NULL,
    [RunStatus] nvarchar(40) NOT NULL,
    [Message] nvarchar(MAX) NULL,
    [ServerName] nvarchar(256) NULL,
    [ExecutionHost] nvarchar(256) NULL,
    [RunStart] datetime NULL,
    [RunEnd] datetime NULL,
    [RowsAffected] int NULL,
    [LogType] nvarchar(100) NULL,
    [LogMessage] nvarchar(MAX) NULL,
    [LogTime] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [log].[AutomationLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'log' AND TABLE_NAME = 'EmailNotificationHistory')
BEGIN
    CREATE TABLE [log].[EmailNotificationHistory] (
    [ID] int NOT NULL IDENTITY(1,1),
    [EventTime] datetime2 NULL DEFAULT (sysdatetime()),
    [ModuleName] nvarchar(400) NULL,
    [StatusText] nvarchar(400) NULL,
    [SubjectLine] nvarchar(1000) NULL,
    [Recipients] nvarchar(1000) NULL,
    [Details] nvarchar(MAX) NULL,
    [ErrorMessage] nvarchar(MAX) NULL
    );
    PRINT 'Created [log].[EmailNotificationHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'log' AND TABLE_NAME = 'JobHistory')
BEGIN
    CREATE TABLE [log].[JobHistory] (
    [JobHistoryID] int NOT NULL IDENTITY(1,1),
    [JobName] nvarchar(510) NULL,
    [RunDate] datetime NOT NULL DEFAULT (getdate()),
    [Status] nvarchar(40) NULL,
    [ServerName] nvarchar(510) NULL,
    [ErrorMessage] nvarchar(MAX) NULL,
    [InsertedOn] datetime NOT NULL DEFAULT (getdate())
    );
    PRINT 'Created [log].[JobHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Logging' AND TABLE_NAME = 'AlertLog')
BEGIN
    CREATE TABLE [Logging].[AlertLog] (
    [AlertID] bigint NOT NULL IDENTITY(1,1),
    [AlertTimestamp] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [AlertType] varchar(50) NOT NULL,
    [Severity] varchar(20) NOT NULL,
    [Category] varchar(50) NOT NULL,
    [Subject] nvarchar(1000) NOT NULL,
    [Message] nvarchar(MAX) NOT NULL,
    [ServerName] nvarchar(256) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [Recipients] nvarchar(2000) NULL,
    [DeliveryStatus] varchar(20) NOT NULL DEFAULT ('Pending'),
    [DeliveryTimestamp] datetime2 NULL,
    [ErrorMessage] nvarchar(4000) NULL,
    [RetryCount] int NOT NULL DEFAULT ((0)),
    [CorrelationID] uniqueidentifier NULL,
    [SourceAlertRule] nvarchar(256) NULL,
    [Acknowledged] bit NOT NULL DEFAULT ((0)),
    [AcknowledgedBy] nvarchar(256) NULL,
    [AcknowledgedTimestamp] datetime2 NULL
    );
    PRINT 'Created [Logging].[AlertLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Logging' AND TABLE_NAME = 'ErrorLog')
BEGIN
    CREATE TABLE [Logging].[ErrorLog] (
    [ErrorID] bigint NOT NULL IDENTITY(1,1),
    [ErrorTimestamp] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [ErrorNumber] int NULL,
    [ErrorSeverity] int NULL,
    [ErrorState] int NULL,
    [ErrorProcedure] nvarchar(256) NULL,
    [ErrorLine] int NULL,
    [ErrorMessage] nvarchar(8000) NOT NULL,
    [ServerName] nvarchar(256) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [UserName] nvarchar(256) NOT NULL DEFAULT (suser_sname()),
    [HostName] nvarchar(256) NULL DEFAULT (host_name()),
    [ApplicationName] nvarchar(256) NULL DEFAULT (app_name()),
    [SourceJob] nvarchar(256) NULL,
    [SourceScript] nvarchar(512) NULL,
    [StackTrace] nvarchar(MAX) NULL,
    [InputParameters] nvarchar(MAX) NULL
    );
    PRINT 'Created [Logging].[ErrorLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Logging' AND TABLE_NAME = 'NotificationConfig')
BEGIN
    CREATE TABLE [Logging].[NotificationConfig] (
    [ConfigID] int NOT NULL IDENTITY(1,1),
    [ConfigName] nvarchar(200) NOT NULL,
    [ConfigType] varchar(50) NOT NULL,
    [ConfigValue] nvarchar(MAX) NOT NULL,
    [IsEnabled] bit NOT NULL DEFAULT ((1)),
    [CreatedDate] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [ModifiedDate] datetime2 NULL,
    [ModifiedBy] nvarchar(256) NULL
    );
    PRINT 'Created [Logging].[NotificationConfig]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Logging' AND TABLE_NAME = 'OperationLog')
BEGIN
    CREATE TABLE [Logging].[OperationLog] (
    [LogID] bigint NOT NULL IDENTITY(1,1),
    [LogTimestamp] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [LogLevel] varchar(20) NOT NULL DEFAULT ('INFO'),
    [Category] varchar(50) NOT NULL,
    [Operation] varchar(100) NOT NULL,
    [ServerName] nvarchar(256) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [Message] nvarchar(8000) NOT NULL,
    [DurationMS] int NULL,
    [RowsAffected] int NULL,
    [ExecutedBy] nvarchar(256) NOT NULL DEFAULT (suser_sname()),
    [SourceJob] nvarchar(256) NULL,
    [SourceScript] nvarchar(512) NULL,
    [AdditionalData] nvarchar(MAX) NULL
    );
    PRINT 'Created [Logging].[OperationLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'meta' AND TABLE_NAME = 'AlertHistory')
BEGIN
    CREATE TABLE [meta].[AlertHistory] (
    [AlertID] int NOT NULL IDENTITY(1,1),
    [AlertTime] datetime2 NULL DEFAULT (getdate()),
    [InstanceName] nvarchar(256) NULL,
    [AlertType] nvarchar(100) NULL,
    [Severity] nvarchar(40) NULL,
    [MetricName] nvarchar(100) NULL,
    [CurrentValue] decimal(18,2) NULL,
    [ThresholdValue] decimal(18,2) NULL,
    [AlertMessage] nvarchar(MAX) NULL,
    [EmailSent] bit NULL DEFAULT ((0))
    );
    PRINT 'Created [meta].[AlertHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'meta' AND TABLE_NAME = 'BackupComplianceLog')
BEGIN
    CREATE TABLE [meta].[BackupComplianceLog] (
    [LogID] int NOT NULL IDENTITY(1,1),
    [ServerName] varchar(200) NULL,
    [Violations] int NULL,
    [ReportTime] datetime2 NULL DEFAULT (sysutcdatetime()),
    [EmailSentTo] varchar(300) NULL,
    [ErrorMessage] nvarchar(MAX) NULL
    );
    PRINT 'Created [meta].[BackupComplianceLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'meta' AND TABLE_NAME = 'Collectors')
BEGIN
    CREATE TABLE [meta].[Collectors] (
    [CollectorName] nvarchar(200) NOT NULL,
    [ProcedureName] nvarchar(400) NULL,
    [FrequencyMinutes] int NULL,
    [IsEnabled] bit NULL DEFAULT ((1)),
    [CreatedOn] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [meta].[Collectors]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'meta' AND TABLE_NAME = 'EmailTemplates')
BEGIN
    CREATE TABLE [meta].[EmailTemplates] (
    [TemplateID] int NOT NULL IDENTITY(1,1),
    [TemplateName] sysname NOT NULL,
    [SubjectLine] nvarchar(800) NULL,
    [BodyHTML] nvarchar(MAX) NULL,
    [CreatedAt] datetime2 NULL DEFAULT (sysutcdatetime())
    );
    PRINT 'Created [meta].[EmailTemplates]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'meta' AND TABLE_NAME = 'ETLExecutionLog')
BEGIN
    CREATE TABLE [meta].[ETLExecutionLog] (
    [LogID] int NOT NULL IDENTITY(1,1),
    [ProcessName] nvarchar(200) NULL,
    [StartTime] datetime2 NULL,
    [EndTime] datetime2 NULL,
    [Status] nvarchar(40) NULL,
    [RowsProcessed] int NULL,
    [ErrorMessage] nvarchar(MAX) NULL
    );
    PRINT 'Created [meta].[ETLExecutionLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'meta' AND TABLE_NAME = 'ExternalProcessThrottleHistory')
BEGIN
    CREATE TABLE [meta].[ExternalProcessThrottleHistory] (
    [HistoryID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [ProcessName] nvarchar(256) NOT NULL,
    [Action] nvarchar(40) NOT NULL,
    [PreviousState] nvarchar(40) NULL,
    [NewState] nvarchar(40) NULL,
    [PreviousPriority] nvarchar(40) NULL,
    [NewPriority] nvarchar(40) NULL,
    [SQLCPUAtAction] decimal(5,2) NULL,
    [ThresholdValue] decimal(5,2) NULL,
    [ActionTime] datetime2 NULL DEFAULT (getdate()),
    [ActionBy] nvarchar(256) NULL DEFAULT ('DBAOps Automated'),
    [ExecutionResult] nvarchar(40) NULL DEFAULT ('Pending'),
    [ErrorMessage] nvarchar(MAX) NULL
    );
    PRINT 'Created [meta].[ExternalProcessThrottleHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'meta' AND TABLE_NAME = 'FactAudit')
BEGIN
    CREATE TABLE [meta].[FactAudit] (
    [AuditID] int NOT NULL IDENTITY(1,1),
    [FactName] nvarchar(200) NOT NULL,
    [ValidationStatus] nvarchar(40) NOT NULL,
    [ValidationTime] datetime2 NOT NULL DEFAULT (sysutcdatetime()),
    [IssueCount] int NOT NULL
    );
    PRINT 'Created [meta].[FactAudit]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'meta' AND TABLE_NAME = 'FactReportAudit')
BEGIN
    CREATE TABLE [meta].[FactReportAudit] (
    [AuditID] int NOT NULL IDENTITY(1,1),
    [RunTime] datetime2 NOT NULL DEFAULT (sysutcdatetime()),
    [RowSummary] nvarchar(MAX) NULL,
    [Status] varchar(50) NULL,
    [ErrorMessage] nvarchar(MAX) NULL
    );
    PRINT 'Created [meta].[FactReportAudit]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'meta' AND TABLE_NAME = 'FactReportLog')
BEGIN
    CREATE TABLE [meta].[FactReportLog] (
    [LogID] int NOT NULL IDENTITY(1,1),
    [ReportTime] datetime2 NOT NULL DEFAULT (sysutcdatetime()),
    [Status] varchar(50) NOT NULL,
    [SentTo] varchar(300) NOT NULL,
    [ErrorMessage] nvarchar(MAX) NULL
    );
    PRINT 'Created [meta].[FactReportLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'metrics' AND TABLE_NAME = 'Baseline_ServerHealth')
BEGIN
    CREATE TABLE [metrics].[Baseline_ServerHealth] (
    [BaselineDate] date NOT NULL,
    [ServerName] sysname NOT NULL,
    [AvgCPU] decimal(10,2) NULL,
    [AvgMemory] decimal(10,2) NULL,
    [AvgTempDB] decimal(10,2) NULL,
    [AvgActiveSessions] int NULL
    );
    PRINT 'Created [metrics].[Baseline_ServerHealth]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'metrics' AND TABLE_NAME = 'FACT_JobHistory')
BEGIN
    CREATE TABLE [metrics].[FACT_JobHistory] (
    [JobHistoryID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [JobName] nvarchar(256) NOT NULL,
    [StepID] int NULL,
    [StepName] nvarchar(256) NULL,
    [RunStatus] int NOT NULL,
    [RunDate] date NOT NULL,
    [RunTime] time NOT NULL,
    [RunDateTime] datetime NULL,
    [RunDurationSeconds] int NULL,
    [ErrorMessage] nvarchar(8000) NULL,
    [RetriesAttempted] int NULL,
    [CollectionTime] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [metrics].[FACT_JobHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'metrics' AND TABLE_NAME = 'FACT_ServerHealth')
BEGIN
    CREATE TABLE [metrics].[FACT_ServerHealth] (
    [RowID] bigint NOT NULL IDENTITY(1,1),
    [CaptureTime] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [ServerName] sysname NOT NULL,
    [CPU_Utilization] decimal(10,2) NULL,
    [CPU_SignalWaitPct] decimal(10,2) NULL,
    [RunnableTasksCount] int NULL,
    [Memory_PLE] int NULL,
    [Memory_GrantsPending] int NULL,
    [Memory_TotalMB] decimal(18,2) NULL,
    [Memory_UsedMB] decimal(18,2) NULL,
    [TempDB_UsageMB] decimal(18,2) NULL,
    [TempDB_VersionStoreMB] decimal(18,2) NULL,
    [TempDB_FreeSpaceMB] decimal(18,2) NULL,
    [ActiveSessions] int NULL,
    [BlockingSessions] int NULL,
    [LongRunningQueries] int NULL,
    [InstanceVersion] varchar(50) NULL,
    [Edition] varchar(200) NULL,
    [UptimeHours] int NULL,
    [BackupAge_Full_Hours] int NULL,
    [BackupAge_Diff_Hours] int NULL,
    [BackupAge_Log_Hours] int NULL,
    [ErrorLog_CriticalCount] int NULL
    );
    PRINT 'Created [metrics].[FACT_ServerHealth]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'metrics' AND TABLE_NAME = 'JobHistory')
BEGIN
    CREATE TABLE [metrics].[JobHistory] (
    [ID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [JobName] nvarchar(512) NULL,
    [StepName] nvarchar(512) NULL,
    [RunDate] datetime NULL,
    [RunTime] int NULL,
    [RunDuration] int NULL,
    [RunStatus] nvarchar(40) NULL,
    [Message] nvarchar(1000) NULL,
    [CollectedAt] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [metrics].[JobHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'metrics' AND TABLE_NAME = 'PerformanceBaseline')
BEGIN
    CREATE TABLE [metrics].[PerformanceBaseline] (
    [BaselineID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [CPUPercent] decimal(5,2) NULL,
    [MemoryUsedMB] int NULL,
    [PLE] int NULL,
    [WaitCategory] nvarchar(100) NULL,
    [WaitSeconds] int NULL,
    [CollectedDate] datetime NULL DEFAULT (getdate()),
    [CaptureTime] datetime NOT NULL DEFAULT (getdate()),
    [TotalMemoryMB] int NULL,
    [CollectionScope] nvarchar(40) NULL DEFAULT ('Hourly')
    );
    PRINT 'Created [metrics].[PerformanceBaseline]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ml' AND TABLE_NAME = 'Models')
BEGIN
    CREATE TABLE [ml].[Models] (
    [ModelID] int NOT NULL IDENTITY(1,1),
    [ModelName] nvarchar(256) NOT NULL,
    [ModelType] nvarchar(120) NOT NULL,
    [IsActive] bit NOT NULL DEFAULT ((1)),
    [TrainedDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [ml].[Models]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'ml' AND TABLE_NAME = 'Predictions')
BEGIN
    CREATE TABLE [ml].[Predictions] (
    [PredictionID] bigint NOT NULL IDENTITY(1,1),
    [ModelID] int NOT NULL,
    [ServerID] int NOT NULL,
    [PredictionType] nvarchar(120) NOT NULL,
    [ConfidenceScore] decimal(5,2) NOT NULL,
    [PredictionMadeDateTime] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [ml].[Predictions]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Monitoring' AND TABLE_NAME = 'JobComplianceCurrentStatus')
BEGIN
    CREATE TABLE [Monitoring].[JobComplianceCurrentStatus] (
    [StatusID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(512) NOT NULL,
    [JobName] nvarchar(512) NOT NULL,
    [DefinitionID] int NOT NULL,
    [ComplianceStatus] nvarchar(40) NOT NULL,
    [LastCheckedDate] datetime NOT NULL,
    [LastFixedDate] datetime NULL,
    [IssueDescription] nvarchar(1000) NULL
    );
    PRINT 'Created [Monitoring].[JobComplianceCurrentStatus]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Monitoring' AND TABLE_NAME = 'JobComplianceDefinitions')
BEGIN
    CREATE TABLE [Monitoring].[JobComplianceDefinitions] (
    [DefinitionID] int NOT NULL IDENTITY(1,1),
    [RuleName] nvarchar(256) NOT NULL,
    [JobNamePattern] nvarchar(512) NOT NULL,
    [Description] nvarchar(1000) NULL,
    [CheckType] nvarchar(100) NOT NULL,
    [Parameter1] nvarchar(256) NULL,
    [Parameter2] nvarchar(256) NULL,
    [FixAction] nvarchar(MAX) NULL,
    [IsActive] bit NOT NULL DEFAULT ((1)),
    [Severity] nvarchar(40) NOT NULL DEFAULT ('Warning'),
    [CreatedDate] datetime NOT NULL DEFAULT (getdate()),
    [ModifiedDate] datetime NULL,
    [CreatedBy] nvarchar(256) NOT NULL DEFAULT (suser_sname())
    );
    PRINT 'Created [Monitoring].[JobComplianceDefinitions]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Monitoring' AND TABLE_NAME = 'JobComplianceResults')
BEGIN
    CREATE TABLE [Monitoring].[JobComplianceResults] (
    [ResultID] int NOT NULL IDENTITY(1,1),
    [ScanID] int NOT NULL,
    [DefinitionID] int NOT NULL,
    [ServerName] nvarchar(512) NOT NULL,
    [JobName] nvarchar(512) NOT NULL,
    [StepID] int NULL,
    [StepName] nvarchar(512) NULL,
    [ComplianceStatus] nvarchar(40) NOT NULL,
    [IssueDescription] nvarchar(1000) NULL,
    [FixApplied] bit NOT NULL DEFAULT ((0)),
    [FixResult] nvarchar(1000) NULL,
    [CheckedDate] datetime NOT NULL DEFAULT (getdate()),
    [FixedDate] datetime NULL
    );
    PRINT 'Created [Monitoring].[JobComplianceResults]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Monitoring' AND TABLE_NAME = 'JobComplianceScanHistory')
BEGIN
    CREATE TABLE [Monitoring].[JobComplianceScanHistory] (
    [ScanID] int NOT NULL IDENTITY(1,1),
    [ScanStartTime] datetime NOT NULL,
    [ScanEndTime] datetime NULL,
    [ServersScanned] int NOT NULL DEFAULT ((0)),
    [ServersAffected] int NOT NULL DEFAULT ((0)),
    [ServersFixed] int NOT NULL DEFAULT ((0)),
    [ServersFailed] int NOT NULL DEFAULT ((0)),
    [ServersUnreachable] int NOT NULL DEFAULT ((0)),
    [AutoFixEnabled] bit NOT NULL DEFAULT ((0)),
    [ScanStatus] nvarchar(40) NOT NULL DEFAULT ('Running'),
    [ErrorMessage] nvarchar(MAX) NULL,
    [ExecutedBy] nvarchar(256) NOT NULL DEFAULT (suser_sname())
    );
    PRINT 'Created [Monitoring].[JobComplianceScanHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Monitoring' AND TABLE_NAME = 'Sql_AuditEvent')
BEGIN
    CREATE TABLE [Monitoring].[Sql_AuditEvent] (
    [Id] bigint NOT NULL IDENTITY(1,1),
    [ServerName] sysname NOT NULL,
    [EventTimeUtc] datetime2 NOT NULL,
    [SessionId] int NULL,
    [LoginName] sysname NULL,
    [DatabaseName] sysname NULL,
    [ObjectName] sysname NULL,
    [Statement] nvarchar(8000) NULL,
    [ActionId] char(4) NULL,
    [Succeeded] bit NULL,
    [ClientIp] varchar(48) NULL,
    [InsertedUtc] datetime2 NOT NULL DEFAULT (sysutcdatetime()),
    [HostName] sysname NULL,
    [SourceLog] nvarchar(64) NOT NULL DEFAULT (N'Application'),
    [LoadTimeUtc] datetime2 NOT NULL DEFAULT (sysutcdatetime())
    );
    PRINT 'Created [Monitoring].[Sql_AuditEvent]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Monitoring' AND TABLE_NAME = 'Sql_AuditEvent_Staging')
BEGIN
    CREATE TABLE [Monitoring].[Sql_AuditEvent_Staging] (
    [StagingId] bigint NOT NULL IDENTITY(1,1),
    [ServerName] sysname NOT NULL,
    [EventTimeUtc] datetime2 NOT NULL,
    [LoginName] nvarchar(512) NOT NULL,
    [DatabaseName] sysname NULL,
    [ObjectName] nvarchar(1024) NULL,
    [ActionId] nvarchar(8) NULL,
    [ClientIp] nvarchar(128) NULL,
    [HostName] nvarchar(512) NULL,
    [Statement] nvarchar(MAX) NULL,
    [SourceLog] nvarchar(64) NOT NULL DEFAULT (N'Application')
    );
    PRINT 'Created [Monitoring].[Sql_AuditEvent_Staging]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'orion' AND TABLE_NAME = 'ServerHealth')
BEGIN
    CREATE TABLE [orion].[ServerHealth] (
    [OrionHealthID] bigint NOT NULL IDENTITY(1,1),
    [ServerID] int NOT NULL,
    [OrionVersion] nvarchar(100) NULL,
    [OrionServiceStatus] nvarchar(40) NULL,
    [OrionDatabaseName] nvarchar(256) NULL,
    [CollectedDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [orion].[ServerHealth]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'patch' AND TABLE_NAME = 'AvailablePatches')
BEGIN
    CREATE TABLE [patch].[AvailablePatches] (
    [PatchID] int NOT NULL IDENTITY(1,1),
    [KBNumber] varchar(20) NOT NULL,
    [Title] nvarchar(1000) NOT NULL,
    [Severity] nvarchar(40) NOT NULL,
    [ReleaseDate] date NOT NULL,
    [CVENumbers] nvarchar(MAX) NULL,
    [CollectedDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [patch].[AvailablePatches]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'patch' AND TABLE_NAME = 'fact_PatchHistory')
BEGIN
    CREATE TABLE [patch].[fact_PatchHistory] (
    [PatchID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [PatchType] nvarchar(100) NOT NULL,
    [FromVersion] nvarchar(100) NULL,
    [FromBuild] nvarchar(100) NULL,
    [ToVersion] nvarchar(100) NOT NULL,
    [ToBuild] nvarchar(100) NOT NULL,
    [BuildsBehindBefore] int NULL,
    [BuildsBehindAfter] int NULL,
    [PatchStatus] nvarchar(40) NOT NULL DEFAULT ('Pending'),
    [ScheduledTime] datetime2 NULL,
    [StartTime] datetime2 NULL,
    [EndTime] datetime2 NULL,
    [Duration] int NULL,
    [InitiatedBy] nvarchar(200) NOT NULL,
    [ApprovalRequired] bit NOT NULL DEFAULT ((0)),
    [ApprovedBy] nvarchar(200) NULL,
    [ApprovalDate] datetime2 NULL,
    [MaintenanceWindowStart] datetime2 NULL,
    [MaintenanceWindowEnd] datetime2 NULL,
    [PrePatchBackupID] int NULL,
    [PrePatchHealthCheck] nvarchar(MAX) NULL,
    [PostPatchHealthCheck] nvarchar(MAX) NULL,
    [HealthCheckPassed] bit NULL,
    [ErrorMessage] nvarchar(MAX) NULL,
    [RollbackReason] nvarchar(1000) NULL,
    [RollbackTime] datetime2 NULL,
    [NotificationSent] bit NOT NULL DEFAULT ((0)),
    [IsProduction] bit NOT NULL DEFAULT ((0)),
    [Environment] nvarchar(100) NOT NULL,
    [ReplicationRole] nvarchar(100) NULL
    );
    PRINT 'Created [patch].[fact_PatchHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'patch' AND TABLE_NAME = 'PatchCompliance')
BEGIN
    CREATE TABLE [patch].[PatchCompliance] (
    [ComplianceID] bigint NOT NULL IDENTITY(1,1),
    [ServerID] int NOT NULL,
    [MissingCriticalPatches] int NULL,
    [ComplianceScore] int NULL,
    [ComplianceStatus] nvarchar(40) NULL,
    [CollectedDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [patch].[PatchCompliance]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'patch' AND TABLE_NAME = 'ServerPatches')
BEGIN
    CREATE TABLE [patch].[ServerPatches] (
    [ServerPatchID] bigint NOT NULL IDENTITY(1,1),
    [ServerID] int NOT NULL,
    [PatchID] int NOT NULL,
    [InstalledDate] datetime NOT NULL,
    [InstallStatus] nvarchar(40) NOT NULL DEFAULT ('Installed'),
    [CollectedDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [patch].[ServerPatches]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'ComplianceConfiguration')
BEGIN
    CREATE TABLE [Patching].[ComplianceConfiguration] (
    [ConfigID] int NOT NULL IDENTITY(1,1),
    [ConfigKey] nvarchar(200) NOT NULL,
    [ConfigValue] nvarchar(1000) NOT NULL,
    [Description] nvarchar(1000) NULL,
    [ComplianceStandard] nvarchar(100) NULL,
    [ModifiedDate] datetime NULL DEFAULT (getdate()),
    [ModifiedBy] nvarchar(256) NULL DEFAULT (suser_sname())
    );
    PRINT 'Created [Patching].[ComplianceConfiguration]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'ComplianceReportLog')
BEGIN
    CREATE TABLE [Patching].[ComplianceReportLog] (
    [ReportID] int NOT NULL IDENTITY(1,1),
    [ReportDate] datetime NULL DEFAULT (getdate()),
    [TotalServers] int NULL,
    [CompliantServers] int NULL,
    [NonCompliantServers] int NULL,
    [WarningServers] int NULL,
    [UnknownServers] int NULL,
    [CompliancePercentage] decimal(5,2) NULL,
    [ReportSentTo] nvarchar(MAX) NULL,
    [ReportStatus] nvarchar(100) NULL,
    [ErrorMessage] nvarchar(MAX) NULL,
    [ExecutionTimeMS] int NULL
    );
    PRINT 'Created [Patching].[ComplianceReportLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'Configuration')
BEGIN
    CREATE TABLE [Patching].[Configuration] (
    [ConfigKey] nvarchar(200) NOT NULL,
    [ConfigValue] nvarchar(1000) NULL,
    [Description] nvarchar(1000) NULL,
    [ModifiedDate] datetime NULL DEFAULT (getdate()),
    [ModifiedBy] nvarchar(256) NULL DEFAULT (suser_sname())
    );
    PRINT 'Created [Patching].[Configuration]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'CUPackages')
BEGIN
    CREATE TABLE [Patching].[CUPackages] (
    [PackageID] int NOT NULL IDENTITY(1,1),
    [SQLVersion] nvarchar(40) NOT NULL,
    [CUNumber] int NOT NULL,
    [CUName] nvarchar(40) NULL,
    [KBNumber] nvarchar(40) NOT NULL,
    [BuildNumber] nvarchar(40) NOT NULL,
    [PackageFileName] nvarchar(512) NOT NULL,
    [PackageSizeMB] int NULL,
    [ReleaseDate] date NULL,
    [IsLatest] bit NULL DEFAULT ((1)),
    [IsActive] bit NULL DEFAULT ((1)),
    [AddedDate] datetime NULL DEFAULT (getdate()),
    [AddedBy] nvarchar(256) NULL DEFAULT (suser_sname()),
    [Notes] nvarchar(1000) NULL
    );
    PRINT 'Created [Patching].[CUPackages]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'DeploymentBatches')
BEGIN
    CREATE TABLE [Patching].[DeploymentBatches] (
    [BatchID] uniqueidentifier NOT NULL DEFAULT (newid()),
    [BatchName] nvarchar(400) NULL,
    [StartTime] datetime NULL DEFAULT (getdate()),
    [EndTime] datetime NULL,
    [TotalServers] int NULL,
    [SuccessCount] int NULL DEFAULT ((0)),
    [FailedCount] int NULL DEFAULT ((0)),
    [SkippedCount] int NULL DEFAULT ((0)),
    [RebootRequiredCount] int NULL DEFAULT ((0)),
    [Status] nvarchar(60) NULL DEFAULT ('Running'),
    [InitiatedBy] nvarchar(256) NULL DEFAULT (suser_sname()),
    [Notes] nvarchar(MAX) NULL
    );
    PRINT 'Created [Patching].[DeploymentBatches]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'DeploymentHistory')
BEGIN
    CREATE TABLE [Patching].[DeploymentHistory] (
    [DeploymentID] int NOT NULL IDENTITY(1,1),
    [QueueID] int NULL,
    [ServerName] nvarchar(256) NOT NULL,
    [PackageID] int NULL,
    [BatchID] uniqueidentifier NULL,
    [PreDeployBuild] nvarchar(100) NULL,
    [PreDeployCU] nvarchar(40) NULL,
    [PreDeployDate] datetime NULL,
    [TargetCU] nvarchar(40) NULL,
    [TargetKB] nvarchar(40) NULL,
    [TargetBuild] nvarchar(100) NULL,
    [PostDeployBuild] nvarchar(100) NULL,
    [PostDeployCU] nvarchar(40) NULL,
    [DeploymentStatus] nvarchar(60) NULL,
    [DeploymentStartTime] datetime NULL,
    [DeploymentEndTime] datetime NULL,
    [DurationMinutes] int NULL,
    [ExitCode] int NULL,
    [RebootRequired] bit NULL DEFAULT ((0)),
    [RebootCompleted] bit NULL DEFAULT ((0)),
    [OSVersion] nvarchar(512) NULL,
    [OSBuild] nvarchar(100) NULL,
    [DiskFreeGB] decimal(10,2) NULL,
    [ActiveConnections] int NULL,
    [LastBackupDate] datetime NULL,
    [DeployedBy] nvarchar(256) NULL DEFAULT (suser_sname()),
    [ErrorMessage] nvarchar(MAX) NULL,
    [Notes] nvarchar(MAX) NULL,
    [CreatedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [Patching].[DeploymentHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'DeploymentQueue')
BEGIN
    CREATE TABLE [Patching].[DeploymentQueue] (
    [QueueID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [PackageID] int NOT NULL,
    [Priority] int NULL DEFAULT ((50)),
    [ScheduledDate] datetime NULL,
    [MaintenanceWindow] nvarchar(100) NULL,
    [RequestedBy] nvarchar(256) NULL DEFAULT (suser_sname()),
    [RequestedDate] datetime NULL DEFAULT (getdate()),
    [ApprovedBy] nvarchar(256) NULL,
    [ApprovedDate] datetime NULL,
    [Status] nvarchar(60) NULL DEFAULT ('Pending'),
    [PreCheckPassed] bit NULL,
    [PreCheckDate] datetime NULL,
    [PreCheckNotes] nvarchar(MAX) NULL,
    [Notes] nvarchar(1000) NULL
    );
    PRINT 'Created [Patching].[DeploymentQueue]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'KnownBuilds')
BEGIN
    CREATE TABLE [Patching].[KnownBuilds] (
    [BuildID] int NOT NULL IDENTITY(1,1),
    [SQLMajorVersion] int NOT NULL,
    [SQLVersionName] nvarchar(100) NOT NULL,
    [ReleaseType] nvarchar(20) NOT NULL,
    [ReleaseName] nvarchar(40) NOT NULL,
    [KBNumber] nvarchar(40) NULL,
    [BuildNumber] nvarchar(40) NOT NULL,
    [ReleaseDate] date NULL,
    [IsSupported] bit NULL DEFAULT ((1)),
    [DateAdded] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [Patching].[KnownBuilds]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'MaintenanceWindows')
BEGIN
    CREATE TABLE [Patching].[MaintenanceWindows] (
    [WindowID] int NOT NULL IDENTITY(1,1),
    [WindowName] varchar(100) NOT NULL,
    [Description] varchar(500) NULL,
    [StartTime] time NOT NULL,
    [DurationMinutes] int NOT NULL DEFAULT ((120)),
    [DayOfWeek] int NULL,
    [WeekOfMonth] int NULL,
    [Environment] varchar(50) NULL,
    [ComplianceTier] varchar(100) NULL,
    [AppCategory] varchar(100) NULL,
    [ServerList] varchar(MAX) NULL,
    [RequiresApproval] bit NULL DEFAULT ((1)),
    [AutoReboot] bit NULL DEFAULT ((0)),
    [NotifyBeforeMinutes] int NULL DEFAULT ((60)),
    [NotifyEmail] varchar(500) NULL,
    [IsActive] bit NULL DEFAULT ((1)),
    [CreatedBy] varchar(100) NULL DEFAULT (suser_sname()),
    [CreatedDate] datetime NULL DEFAULT (getdate()),
    [ModifiedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [Patching].[MaintenanceWindows]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'MicrosoftKBReference')
BEGIN
    CREATE TABLE [Patching].[MicrosoftKBReference] (
    [KBID] int NOT NULL IDENTITY(1,1),
    [KBNumber] varchar(20) NOT NULL,
    [SQLMajorVersion] int NOT NULL,
    [SQLVersionName] varchar(50) NOT NULL,
    [PatchType] varchar(50) NOT NULL,
    [CumulativeUpdate] varchar(20) NULL,
    [BuildNumber] varchar(50) NOT NULL,
    [ReleaseDate] date NOT NULL,
    [IsSecurityUpdate] bit NOT NULL DEFAULT ((0)),
    [CVENumbers] varchar(1000) NULL,
    [SecuritySeverity] varchar(20) NULL,
    [DownloadURL] varchar(1000) NULL,
    [FileSize] varchar(50) NULL,
    [Title] varchar(500) NOT NULL,
    [Description] varchar(MAX) NULL,
    [KnownIssues] varchar(MAX) NULL,
    [Prerequisites] varchar(500) NULL,
    [IsLatest] bit NOT NULL DEFAULT ((0)),
    [IsSuperseded] bit NOT NULL DEFAULT ((0)),
    [SupersededBy] varchar(20) NULL,
    [LastUpdated] datetime NOT NULL DEFAULT (getdate())
    );
    PRINT 'Created [Patching].[MicrosoftKBReference]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'MicrosoftReleases')
BEGIN
    CREATE TABLE [Patching].[MicrosoftReleases] (
    [ReleaseID] int NOT NULL IDENTITY(1,1),
    [SQLMajorVersion] int NOT NULL,
    [SQLVersionName] nvarchar(100) NOT NULL,
    [ReleaseType] nvarchar(40) NOT NULL,
    [ReleaseName] nvarchar(40) NOT NULL,
    [KBNumber] nvarchar(40) NOT NULL,
    [BuildNumber] nvarchar(40) NOT NULL,
    [ReleaseDate] date NOT NULL,
    [DownloadURL] nvarchar(1000) NULL,
    [ReleaseNotes] nvarchar(MAX) NULL,
    [SecurityFixes] int NULL DEFAULT ((0)),
    [BugFixes] int NULL DEFAULT ((0)),
    [IsCritical] bit NULL DEFAULT ((0)),
    [IsLatest] bit NULL DEFAULT ((0)),
    [DateAdded] datetime NULL DEFAULT (getdate()),
    [AddedBy] nvarchar(200) NULL DEFAULT (suser_sname())
    );
    PRINT 'Created [Patching].[MicrosoftReleases]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'PatchCalendar')
BEGIN
    CREATE TABLE [Patching].[PatchCalendar] (
    [CalendarID] int NOT NULL IDENTITY(1,1),
    [CalendarYear] int NOT NULL,
    [CalendarMonth] int NOT NULL,
    [CalendarDay] int NOT NULL,
    [CalendarDate] date NOT NULL,
    [DayOfWeek] varchar(20) NOT NULL,
    [WeekOfMonth] int NOT NULL,
    [WeekOfYear] int NOT NULL,
    [IsWeekend] bit NOT NULL DEFAULT ((0)),
    [IsHoliday] bit NOT NULL DEFAULT ((0)),
    [HolidayName] varchar(100) NULL,
    [IsPatchTuesday] bit NOT NULL DEFAULT ((0)),
    [IsMaintenanceWindow] bit NOT NULL DEFAULT ((0)),
    [MaintenanceWindowID] int NULL,
    [Notes] varchar(500) NULL
    );
    PRINT 'Created [Patching].[PatchCalendar]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'PatchDownloadURLs')
BEGIN
    CREATE TABLE [Patching].[PatchDownloadURLs] (
    [URLID] int NOT NULL IDENTITY(1,1),
    [SQLVersion] varchar(20) NULL,
    [CUVersion] varchar(20) NULL,
    [KBNumber] varchar(20) NULL,
    [DownloadURL] varchar(1000) NULL,
    [FileName] varchar(200) NULL,
    [FileSizeMB] int NULL,
    [ReleaseDate] date NULL,
    [IsActive] bit NULL DEFAULT ((1))
    );
    PRINT 'Created [Patching].[PatchDownloadURLs]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'PatchExecutionHistory')
BEGIN
    CREATE TABLE [Patching].[PatchExecutionHistory] (
    [ExecutionID] int NOT NULL IDENTITY(1,1),
    [ScheduleID] int NULL,
    [ServerName] varchar(128) NOT NULL,
    [BeforeBuild] varchar(50) NULL,
    [BeforeCU] varchar(20) NULL,
    [BeforeProductVersion] varchar(50) NULL,
    [AfterBuild] varchar(50) NULL,
    [AfterCU] varchar(20) NULL,
    [AfterProductVersion] varchar(50) NULL,
    [PatchType] varchar(50) NOT NULL,
    [KBNumber] varchar(20) NULL,
    [PatchFileName] varchar(500) NULL,
    [StartTime] datetime NOT NULL,
    [EndTime] datetime NULL,
    [DurationMinutes] int NULL,
    [Status] varchar(50) NOT NULL,
    [RebootRequired] bit NULL,
    [RebootCompleted] bit NULL,
    [ServicesRestarted] bit NULL,
    [InstallLog] varchar(MAX) NULL,
    [ErrorLog] varchar(MAX) NULL,
    [ExecutedBy] varchar(100) NOT NULL DEFAULT (suser_sname()),
    [ExecutionMethod] varchar(50) NULL
    );
    PRINT 'Created [Patching].[PatchExecutionHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'PatchExecutionQueue')
BEGIN
    CREATE TABLE [Patching].[PatchExecutionQueue] (
    [QueueID] int NOT NULL IDENTITY(1,1),
    [ScheduleID] int NULL,
    [ServerName] varchar(128) NOT NULL,
    [InstanceName] varchar(128) NOT NULL DEFAULT ('MSSQLSERVER'),
    [PatchFilePath] varchar(500) NOT NULL,
    [KBNumber] varchar(20) NULL,
    [PatchType] varchar(50) NOT NULL DEFAULT ('CU'),
    [QueueStatus] varchar(50) NOT NULL DEFAULT ('Queued'),
    [Priority] int NOT NULL DEFAULT ((5)),
    [QueuedDate] datetime NOT NULL DEFAULT (getdate()),
    [QueuedBy] varchar(100) NOT NULL DEFAULT (suser_sname()),
    [ScheduledExecutionTime] datetime NULL,
    [StartedDate] datetime NULL,
    [CompletedDate] datetime NULL,
    [ExitCode] int NULL,
    [ResultMessage] varchar(MAX) NULL,
    [LogFilePath] varchar(500) NULL
    );
    PRINT 'Created [Patching].[PatchExecutionQueue]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'PatchHistory')
BEGIN
    CREATE TABLE [Patching].[PatchHistory] (
    [HistoryID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [PatchDate] datetime NOT NULL,
    [PatchType] nvarchar(100) NULL,
    [KBNumber] nvarchar(40) NULL,
    [BuildBefore] nvarchar(100) NULL,
    [BuildAfter] nvarchar(100) NULL,
    [Status] nvarchar(100) NULL,
    [ExecutedBy] nvarchar(200) NULL,
    [Notes] nvarchar(2000) NULL
    );
    PRINT 'Created [Patching].[PatchHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'PatchingReportLog')
BEGIN
    CREATE TABLE [Patching].[PatchingReportLog] (
    [ReportID] int NOT NULL IDENTITY(1,1),
    [ReportDate] datetime NULL DEFAULT (getdate()),
    [ReportType] nvarchar(100) NOT NULL,
    [TotalServers] int NULL,
    [ServersCompliant] int NULL,
    [ServersNeedingPatches] int NULL,
    [ServersPendingNonProd] int NULL,
    [ServersPendingProd] int NULL,
    [OverallComplianceRate] decimal(5,2) NULL,
    [ReportSentTo] nvarchar(MAX) NULL,
    [ReportStatus] nvarchar(40) NULL,
    [ErrorMessage] nvarchar(MAX) NULL
    );
    PRINT 'Created [Patching].[PatchingReportLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'PatchingSchedule')
BEGIN
    CREATE TABLE [Patching].[PatchingSchedule] (
    [ScheduleID] int NOT NULL IDENTITY(1,1),
    [PatchCycleMonth] date NOT NULL,
    [PatchTuesday] date NOT NULL,
    [NonProdPatchDate] date NOT NULL,
    [ProdPatchDate] date NOT NULL,
    [NonProdPatchWindow] nvarchar(100) NULL DEFAULT ('02:00 AM - 06:00 AM'),
    [ProdPatchWindow] nvarchar(100) NULL DEFAULT ('02:00 AM - 06:00 AM'),
    [NonProdStatus] nvarchar(40) NULL DEFAULT ('Pending'),
    [ProdStatus] nvarchar(40) NULL DEFAULT ('Pending'),
    [NonProdCompletedDate] datetime NULL,
    [ProdCompletedDate] datetime NULL,
    [Notes] nvarchar(MAX) NULL,
    [CreatedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [Patching].[PatchingSchedule]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'PatchRequests')
BEGIN
    CREATE TABLE [Patching].[PatchRequests] (
    [RequestID] int NOT NULL IDENTITY(1,1),
    [RequestType] varchar(20) NOT NULL,
    [ServerName] varchar(128) NULL,
    [ServerGroup] varchar(100) NULL,
    [GroupType] varchar(20) NULL,
    [ServerList] varchar(MAX) NULL,
    [TargetBuild] varchar(20) NULL,
    [TargetCU] varchar(20) NULL,
    [KBArticle] varchar(20) NULL,
    [MaintenanceWindowID] int NULL,
    [ScheduledStart] datetime NULL,
    [ScheduledEnd] datetime NULL,
    [Status] varchar(30) NULL DEFAULT ('Pending'),
    [ApprovedBy] varchar(100) NULL,
    [ApprovedDate] datetime NULL,
    [StartedDate] datetime NULL,
    [CompletedDate] datetime NULL,
    [ServersTotal] int NULL DEFAULT ((0)),
    [ServersCompleted] int NULL DEFAULT ((0)),
    [ServersFailed] int NULL DEFAULT ((0)),
    [ErrorLog] varchar(MAX) NULL,
    [RequestedBy] varchar(100) NULL DEFAULT (suser_sname()),
    [RequestedDate] datetime NULL DEFAULT (getdate()),
    [Notes] varchar(1000) NULL
    );
    PRINT 'Created [Patching].[PatchRequests]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'PatchSchedule')
BEGIN
    CREATE TABLE [Patching].[PatchSchedule] (
    [ScheduleID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [SQLVersion] nvarchar(100) NULL,
    [ScheduledDate] datetime NOT NULL,
    [MaintenanceWindowID] int NULL,
    [PatchType] nvarchar(100) NULL DEFAULT ('CU'),
    [CurrentBuild] nvarchar(100) NULL,
    [TargetBuild] nvarchar(100) NULL,
    [TargetCU] nvarchar(40) NULL,
    [KBNumber] nvarchar(40) NULL,
    [DownloadURL] nvarchar(2000) NULL,
    [Status] nvarchar(100) NULL DEFAULT ('Scheduled'),
    [Priority] nvarchar(40) NULL DEFAULT ('Normal'),
    [Environment] nvarchar(100) NULL,
    [ComplianceTier] nvarchar(200) NULL,
    [ApprovedBy] nvarchar(200) NULL,
    [ApprovedDate] datetime NULL,
    [ChangeTicket] nvarchar(100) NULL,
    [PrePatchScore] int NULL,
    [PostPatchScore] int NULL,
    [ExecutionLog] nvarchar(MAX) NULL,
    [Notes] nvarchar(2000) NULL,
    [CreatedDate] datetime NULL DEFAULT (getdate()),
    [CreatedBy] nvarchar(200) NULL,
    [CompletedDate] datetime NULL
    );
    PRINT 'Created [Patching].[PatchSchedule]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'ReleaseDetectionLog')
BEGIN
    CREATE TABLE [Patching].[ReleaseDetectionLog] (
    [DetectionID] int NOT NULL IDENTITY(1,1),
    [DetectionDate] datetime NULL DEFAULT (getdate()),
    [SQLMajorVersion] int NOT NULL,
    [SQLVersionName] nvarchar(100) NOT NULL,
    [DetectedRelease] nvarchar(40) NOT NULL,
    [DetectedKB] nvarchar(40) NOT NULL,
    [DetectedBuild] nvarchar(40) NOT NULL,
    [DetectedReleaseDate] date NULL,
    [CurrentRelease] nvarchar(40) NULL,
    [CurrentKB] nvarchar(40) NULL,
    [IsNewRelease] bit NULL DEFAULT ((0)),
    [NotificationSent] bit NULL DEFAULT ((0)),
    [NotificationDate] datetime NULL,
    [ApprovedBy] nvarchar(200) NULL,
    [ApprovedDate] datetime NULL,
    [AppliedDate] datetime NULL,
    [DetectionSource] nvarchar(200) NULL DEFAULT ('Manual'),
    [RawResponseData] nvarchar(MAX) NULL,
    [Notes] nvarchar(1000) NULL
    );
    PRINT 'Created [Patching].[ReleaseDetectionLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'ScheduledPatches')
BEGIN
    CREATE TABLE [Patching].[ScheduledPatches] (
    [ScheduleID] int NOT NULL IDENTITY(1,1),
    [ScheduleName] varchar(200) NOT NULL,
    [ScheduleType] varchar(50) NOT NULL,
    [ServerName] varchar(128) NULL,
    [GroupID] int NULL,
    [Environment] varchar(50) NULL,
    [ComplianceTier] varchar(50) NULL,
    [PatchType] varchar(50) NOT NULL,
    [TargetBuild] varchar(50) NULL,
    [TargetCU] varchar(20) NULL,
    [KBNumber] varchar(20) NULL,
    [CVENumbers] varchar(500) NULL,
    [MicrosoftDownloadURL] varchar(1000) NULL,
    [ScheduledDate] date NOT NULL,
    [ScheduledStartTime] time NOT NULL,
    [ScheduledEndTime] time NOT NULL,
    [MaintenanceWindowID] int NULL,
    [Status] varchar(50) NOT NULL DEFAULT ('Pending'),
    [ApprovalStatus] varchar(50) NOT NULL DEFAULT ('Pending'),
    [ApprovedBy] varchar(100) NULL,
    [ApprovedDate] datetime NULL,
    [ChangeTicketNumber] varchar(50) NULL,
    [ChangeTicketURL] varchar(500) NULL,
    [BusinessJustification] varchar(1000) NULL,
    [RollbackPlan] varchar(2000) NULL,
    [ActualStartTime] datetime NULL,
    [ActualEndTime] datetime NULL,
    [ExecutedBy] varchar(100) NULL,
    [ExecutionLog] varchar(MAX) NULL,
    [ErrorMessage] varchar(MAX) NULL,
    [PreChecksPassed] bit NULL,
    [PreChecksLog] varchar(MAX) NULL,
    [PostChecksPassed] bit NULL,
    [PostChecksLog] varchar(MAX) NULL,
    [NotifyOnStart] bit NOT NULL DEFAULT ((1)),
    [NotifyOnComplete] bit NOT NULL DEFAULT ((1)),
    [NotifyOnFailure] bit NOT NULL DEFAULT ((1)),
    [NotificationEmails] varchar(500) NULL,
    [CreatedBy] varchar(100) NOT NULL DEFAULT (suser_sname()),
    [CreatedDate] datetime NOT NULL DEFAULT (getdate()),
    [ModifiedBy] varchar(100) NULL,
    [ModifiedDate] datetime NULL
    );
    PRINT 'Created [Patching].[ScheduledPatches]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'ServerAliases')
BEGIN
    CREATE TABLE [Patching].[ServerAliases] (
    [AliasID] int NOT NULL IDENTITY(1,1),
    [PrimaryServerName] nvarchar(256) NOT NULL,
    [AliasServerName] nvarchar(256) NOT NULL,
    [AliasSource] nvarchar(100) NULL,
    [Notes] nvarchar(1000) NULL,
    [IsActive] bit NULL DEFAULT ((1)),
    [CreatedDate] datetime NULL DEFAULT (getdate()),
    [CreatedBy] nvarchar(200) NULL DEFAULT (suser_sname())
    );
    PRINT 'Created [Patching].[ServerAliases]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'ServerGroupMembers')
BEGIN
    CREATE TABLE [Patching].[ServerGroupMembers] (
    [MemberID] int NOT NULL IDENTITY(1,1),
    [GroupID] int NOT NULL,
    [ServerName] varchar(128) NOT NULL,
    [PatchOrder] int NOT NULL DEFAULT ((1)),
    [IsActive] bit NOT NULL DEFAULT ((1)),
    [AddedBy] varchar(100) NOT NULL DEFAULT (suser_sname()),
    [AddedDate] datetime NOT NULL DEFAULT (getdate())
    );
    PRINT 'Created [Patching].[ServerGroupMembers]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'ServerPatchGroups')
BEGIN
    CREATE TABLE [Patching].[ServerPatchGroups] (
    [GroupID] int NOT NULL IDENTITY(1,1),
    [GroupName] varchar(100) NOT NULL,
    [GroupDescription] varchar(500) NULL,
    [Environment] varchar(50) NULL,
    [ComplianceTier] varchar(50) NULL,
    [PatchPriority] int NOT NULL DEFAULT ((3)),
    [DefaultMaintenanceWindowID] int NULL,
    [RequiresApproval] bit NOT NULL DEFAULT ((1)),
    [RequiresChangeTicket] bit NOT NULL DEFAULT ((1)),
    [MaxConcurrentPatches] int NOT NULL DEFAULT ((2)),
    [PatchSequenceOrder] int NOT NULL DEFAULT ((100)),
    [IsActive] bit NOT NULL DEFAULT ((1)),
    [CreatedBy] varchar(100) NOT NULL DEFAULT (suser_sname()),
    [CreatedDate] datetime NOT NULL DEFAULT (getdate()),
    [ModifiedBy] varchar(100) NULL,
    [ModifiedDate] datetime NULL
    );
    PRINT 'Created [Patching].[ServerPatchGroups]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'ServerPatchingCycle')
BEGIN
    CREATE TABLE [Patching].[ServerPatchingCycle] (
    [CycleID] int NOT NULL IDENTITY(1,1),
    [ScheduleID] int NOT NULL,
    [ServerName] nvarchar(256) NOT NULL,
    [ServerEnvironment] nvarchar(100) NOT NULL,
    [SQLMajorVersion] int NULL,
    [CurrentBuildBefore] nvarchar(40) NULL,
    [CurrentCUBefore] nvarchar(40) NULL,
    [TargetBuild] nvarchar(40) NULL,
    [TargetCU] nvarchar(40) NULL,
    [TargetKB] nvarchar(40) NULL,
    [ScheduledDate] date NULL,
    [PatchStatus] nvarchar(60) NULL DEFAULT ('Pending'),
    [PatchedDate] datetime NULL,
    [CurrentBuildAfter] nvarchar(40) NULL,
    [CurrentCUAfter] nvarchar(40) NULL,
    [PatchSuccess] bit NULL,
    [FailureReason] nvarchar(1000) NULL,
    [ExclusionReason] nvarchar(1000) NULL,
    [CreatedDate] datetime NULL DEFAULT (getdate()),
    [ModifiedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [Patching].[ServerPatchingCycle]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'ServerPatchStatus')
BEGIN
    CREATE TABLE [Patching].[ServerPatchStatus] (
    [PatchStatusID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(510) NOT NULL,
    [CurrentBuild] nvarchar(100) NULL,
    [LatestBuild] nvarchar(100) NULL,
    [LatestCU] nvarchar(100) NULL,
    [LastPatchDate] datetime NULL,
    [IsCompliant] bit NULL DEFAULT ((0)),
    [DaysBehind] int NULL DEFAULT ((0)),
    [PatchSource] nvarchar(200) NULL,
    [TaniumTagStatus] nvarchar(200) NULL,
    [NextMaintenanceWindow] datetime NULL,
    [ApprovedForPatching] bit NULL DEFAULT ((0)),
    [PatchNotes] nvarchar(MAX) NULL,
    [CollectedAt] datetime NULL DEFAULT (getdate()),
    [LastUpdated] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [Patching].[ServerPatchStatus]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'SQLBuildReference')
BEGIN
    CREATE TABLE [Patching].[SQLBuildReference] (
    [BuildID] int NOT NULL IDENTITY(1,1),
    [SQLMajorVersion] int NOT NULL,
    [VersionName] varchar(50) NOT NULL,
    [BuildNumber] varchar(20) NOT NULL,
    [CumulativeUpdate] varchar(20) NULL,
    [KBArticle] varchar(20) NULL,
    [ReleaseDate] date NULL,
    [ReleaseType] varchar(20) NOT NULL,
    [IsLatest] bit NULL DEFAULT ((0)),
    [IsSecurityUpdate] bit NULL DEFAULT ((0)),
    [SupportStatus] varchar(30) NULL DEFAULT ('Supported'),
    [EndOfSupportDate] date NULL,
    [DownloadURL] varchar(500) NULL,
    [ReleaseNotes] varchar(500) NULL,
    [CreatedDate] datetime NULL DEFAULT (getdate()),
    [ModifiedDate] datetime NULL DEFAULT (getdate()),
    [CUNumber] int NULL,
    [KBNumber] nvarchar(40) NULL
    );
    PRINT 'Created [Patching].[SQLBuildReference]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'SQLServerBuildReference')
BEGIN
    CREATE TABLE [Patching].[SQLServerBuildReference] (
    [BuildRefID] int NOT NULL IDENTITY(1,1),
    [SQLMajorVersion] int NOT NULL,
    [SQLVersionName] nvarchar(100) NOT NULL,
    [ServicePack] nvarchar(40) NULL,
    [LatestCU] nvarchar(40) NULL,
    [LatestBuildNumber] nvarchar(40) NOT NULL,
    [LatestGDR] nvarchar(40) NULL,
    [ReleaseDate] date NULL,
    [EndOfSupport] date NULL,
    [IsSupported] bit NULL DEFAULT ((1)),
    [LastUpdated] datetime NULL DEFAULT (getdate()),
    [Notes] nvarchar(1000) NULL,
    [KBNumber] nvarchar(40) NULL,
    [DownloadURL] nvarchar(1000) NULL,
    [SupportStatus] nvarchar(200) NULL
    );
    PRINT 'Created [Patching].[SQLServerBuildReference]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'StatusReference')
BEGIN
    CREATE TABLE [Patching].[StatusReference] (
    [StatusID] int NOT NULL IDENTITY(1,1),
    [StatusCode] nvarchar(100) NOT NULL,
    [StatusDisplayName] nvarchar(200) NOT NULL,
    [StatusDescription] nvarchar(1000) NOT NULL,
    [StatusCategory] nvarchar(100) NOT NULL,
    [Severity] int NULL DEFAULT ((0)),
    [IconEmoji] nvarchar(20) NULL,
    [ColorCode] nvarchar(40) NULL,
    [ActionRequired] nvarchar(1000) NULL,
    [IsActive] bit NULL DEFAULT ((1))
    );
    PRINT 'Created [Patching].[StatusReference]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'TaniumJobStatus')
BEGIN
    CREATE TABLE [Patching].[TaniumJobStatus] (
    [JobStatusID] int NOT NULL IDENTITY(1,1),
    [JobName] nvarchar(512) NOT NULL,
    [JobEnabled] bit NULL,
    [LastRunDate] datetime NULL,
    [LastRunStatus] nvarchar(100) NULL,
    [LastRunDuration] int NULL,
    [NextRunDate] datetime NULL,
    [ScheduleEnabled] bit NULL,
    [CheckedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [Patching].[TaniumJobStatus]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'TaniumPatchHistory')
BEGIN
    CREATE TABLE [Patching].[TaniumPatchHistory] (
    [HistoryID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [SQLVersion] nvarchar(512) NULL,
    [CurrentBuildNumber] nvarchar(100) NULL,
    [CurrentCULevel] nvarchar(100) NULL,
    [MissingPatches] int NULL,
    [ComplianceStatus] nvarchar(40) NULL,
    [DaysSinceLastPatch] int NULL,
    [RecordedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [Patching].[TaniumPatchHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'TaniumPatchStatus')
BEGIN
    CREATE TABLE [Patching].[TaniumPatchStatus] (
    [PatchStatusID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [SQLVersion] nvarchar(512) NULL,
    [SQLEdition] nvarchar(256) NULL,
    [CurrentBuildNumber] nvarchar(100) NULL,
    [CurrentCULevel] nvarchar(100) NULL,
    [LatestAvailableCU] nvarchar(100) NULL,
    [LatestAvailableBuild] nvarchar(100) NULL,
    [MissingPatches] int NULL DEFAULT ((0)),
    [MissingCriticalPatches] int NULL DEFAULT ((0)),
    [LastPatchDate] datetime NULL,
    [DaysSinceLastPatch] int NULL,
    [TaniumLastScanDate] datetime NULL,
    [TaniumAgentStatus] nvarchar(100) NULL,
    [ComplianceStatus] nvarchar(40) NULL DEFAULT ('Unknown'),
    [ComplianceNotes] nvarchar(MAX) NULL,
    [IsActive] bit NULL DEFAULT ((1)),
    [CreatedDate] datetime NULL DEFAULT (getdate()),
    [ModifiedDate] datetime NULL DEFAULT (getdate()),
    [ServerEnvironment] nvarchar(100) NULL,
    [TaniumPatchingTag] nvarchar(200) NULL,
    [TaniumPatchingConfigured] bit NULL DEFAULT ((0)),
    [TaniumTagLastChecked] datetime NULL,
    [IsReplicationPublisher] bit NULL DEFAULT ((0)),
    [IsReplicationSubscriber] bit NULL DEFAULT ((0)),
    [ExpectedTaniumTag] nvarchar(200) NULL,
    [TaniumTagMismatch] bit NULL DEFAULT ((0)),
    [NonComplianceReason] nvarchar(1000) NULL,
    [ProposedSolution] nvarchar(1000) NULL,
    [ExcludeFromTaniumAutomation] bit NULL DEFAULT ((0)),
    [ExclusionReason] nvarchar(1000) NULL,
    [OfflineReason] nvarchar(400) NULL,
    [SQLConnectivityStatus] nvarchar(100) NULL
    );
    PRINT 'Created [Patching].[TaniumPatchStatus]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'TaniumReportLog')
BEGIN
    CREATE TABLE [Patching].[TaniumReportLog] (
    [ReportID] int NOT NULL IDENTITY(1,1),
    [ReportDate] datetime NULL DEFAULT (getdate()),
    [TotalServers] int NULL,
    [FullyCompliant] int NULL,
    [PatchCompliant] int NULL,
    [TaniumConfigured] int NULL,
    [TaniumNotConfigured] int NULL,
    [PatchBehind] int NULL,
    [OfflineServers] int NULL,
    [OverallCompliancePct] decimal(5,2) NULL,
    [ReportSentTo] nvarchar(MAX) NULL,
    [ReportStatus] nvarchar(100) NULL,
    [ErrorMessage] nvarchar(MAX) NULL
    );
    PRINT 'Created [Patching].[TaniumReportLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'Patching' AND TABLE_NAME = 'TaniumTagReference')
BEGIN
    CREATE TABLE [Patching].[TaniumTagReference] (
    [TagID] int NOT NULL IDENTITY(1,1),
    [TagCode] int NOT NULL,
    [TagName] nvarchar(200) NOT NULL,
    [TagDescription] nvarchar(1000) NULL,
    [RegistryPath] nvarchar(1000) NOT NULL,
    [IsProduction] bit NULL DEFAULT ((0)),
    [PatchWindow] nvarchar(200) NULL,
    [Notes] nvarchar(1000) NULL
    );
    PRINT 'Created [Patching].[TaniumTagReference]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'pbi' AND TABLE_NAME = 'DimDate')
BEGIN
    CREATE TABLE [pbi].[DimDate] (
    [DateKey] int NOT NULL,
    [FullDate] date NOT NULL,
    [DayOfMonth] tinyint NOT NULL,
    [DayName] varchar(10) NOT NULL,
    [DayOfWeek] tinyint NOT NULL,
    [DayOfYear] smallint NOT NULL,
    [WeekOfYear] tinyint NOT NULL,
    [MonthNumber] tinyint NOT NULL,
    [MonthName] varchar(10) NOT NULL,
    [MonthShort] char(3) NOT NULL,
    [Quarter] tinyint NOT NULL,
    [QuarterName] varchar(6) NOT NULL,
    [Year] smallint NOT NULL,
    [YearMonth] varchar(7) NOT NULL,
    [YearQuarter] varchar(7) NOT NULL,
    [IsWeekend] bit NOT NULL,
    [IsCurrentDay] bit NOT NULL,
    [IsCurrentWeek] bit NOT NULL,
    [IsCurrentMonth] bit NOT NULL,
    [IsCurrentYear] bit NOT NULL,
    [RelativeDayOffset] int NOT NULL,
    [RelativeMonthOffset] int NOT NULL
    );
    PRINT 'Created [pbi].[DimDate]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'perf' AND TABLE_NAME = 'DuplicateIndexes')
BEGIN
    CREATE TABLE [perf].[DuplicateIndexes] (
    [DuplicateID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [TableName] nvarchar(512) NOT NULL,
    [Index1Name] nvarchar(512) NOT NULL,
    [Index2Name] nvarchar(512) NOT NULL,
    [DuplicateType] nvarchar(100) NULL,
    [DropStatement] nvarchar(MAX) NULL,
    [DetectedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [perf].[DuplicateIndexes]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'perf' AND TABLE_NAME = 'ExpensiveQueries')
BEGIN
    CREATE TABLE [perf].[ExpensiveQueries] (
    [QueryID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [QueryText] nvarchar(MAX) NULL,
    [ExecutionCount] bigint NULL,
    [TotalCPU_ms] bigint NULL,
    [TotalDuration_ms] bigint NULL,
    [TotalLogicalReads] bigint NULL,
    [LastExecuted] datetime NULL,
    [CollectedAt] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [perf].[ExpensiveQueries]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'perf' AND TABLE_NAME = 'IndexUsageStats')
BEGIN
    CREATE TABLE [perf].[IndexUsageStats] (
    [IndexUsageID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [TableName] nvarchar(512) NOT NULL,
    [IndexName] nvarchar(512) NULL,
    [UserSeeks] bigint NULL,
    [UserScans] bigint NULL,
    [UserLookups] bigint NULL,
    [UserUpdates] bigint NULL,
    [SizeKB] bigint NULL,
    [FragmentationPercent] decimal(5,2) NULL,
    [CollectedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [perf].[IndexUsageStats]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'perf' AND TABLE_NAME = 'LockEscalations')
BEGIN
    CREATE TABLE [perf].[LockEscalations] (
    [EscalationID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [ObjectName] nvarchar(512) NULL,
    [EscalationType] nvarchar(100) NULL,
    [SPID] int NULL,
    [LoginName] nvarchar(256) NULL,
    [QueryText] nvarchar(MAX) NULL,
    [EventTime] datetime2 NOT NULL
    );
    PRINT 'Created [perf].[LockEscalations]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'perf' AND TABLE_NAME = 'MissingIndexes')
BEGIN
    CREATE TABLE [perf].[MissingIndexes] (
    [MissingIndexID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [TableName] nvarchar(512) NOT NULL,
    [EqualityColumns] nvarchar(MAX) NULL,
    [InequalityColumns] nvarchar(MAX) NULL,
    [IncludedColumns] nvarchar(MAX) NULL,
    [ImprovementMeasure] decimal(18,2) NULL,
    [CreateIndexStatement] nvarchar(MAX) NULL,
    [CollectedAt] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [IsImplemented] bit NOT NULL DEFAULT ((0))
    );
    PRINT 'Created [perf].[MissingIndexes]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'perf' AND TABLE_NAME = 'ParameterSniffingIssues')
BEGIN
    CREATE TABLE [perf].[ParameterSniffingIssues] (
    [IssueID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [ProcedureName] nvarchar(512) NULL,
    [QueryText] nvarchar(MAX) NULL,
    [EstimatedRows] decimal(18,2) NULL,
    [ActualRows] decimal(18,2) NULL,
    [RowEstimateVariance] decimal(18,2) NULL,
    [DetectedAt] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [IsResolved] bit NOT NULL DEFAULT ((0))
    );
    PRINT 'Created [perf].[ParameterSniffingIssues]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'perf' AND TABLE_NAME = 'PerformanceBaseline')
BEGIN
    CREATE TABLE [perf].[PerformanceBaseline] (
    [BaselineID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [MetricName] nvarchar(200) NOT NULL,
    [HourOfDay] tinyint NULL,
    [AvgValue] decimal(18,4) NULL,
    [MinValue] decimal(18,4) NULL,
    [MaxValue] decimal(18,4) NULL,
    [StdDeviation] decimal(18,4) NULL,
    [Percentile95] decimal(18,4) NULL,
    [LastUpdated] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [perf].[PerformanceBaseline]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'perf' AND TABLE_NAME = 'QueryPlans')
BEGIN
    CREATE TABLE [perf].[QueryPlans] (
    [PlanID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [QueryHash] varbinary NULL,
    [QueryPlanXML] xml NULL,
    [HasMissingIndex] bit NULL,
    [HasWarnings] bit NULL,
    [IsParallel] bit NULL,
    [FirstCaptured] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [perf].[QueryPlans]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'perf' AND TABLE_NAME = 'QueryRegressions')
BEGIN
    CREATE TABLE [perf].[QueryRegressions] (
    [RegressionID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [QueryHash] varbinary NULL,
    [QueryText] nvarchar(MAX) NULL,
    [BaselineAvgDurationMs] decimal(18,2) NULL,
    [CurrentAvgDurationMs] decimal(18,2) NULL,
    [DurationIncreasePercent] decimal(18,2) NULL,
    [RegressionType] nvarchar(100) NULL,
    [DetectedAt] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [IsResolved] bit NOT NULL DEFAULT ((0))
    );
    PRINT 'Created [perf].[QueryRegressions]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'perf' AND TABLE_NAME = 'QueryStoreMetrics')
BEGIN
    CREATE TABLE [perf].[QueryStoreMetrics] (
    [MetricID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [QueryID] bigint NOT NULL,
    [QueryText] nvarchar(MAX) NULL,
    [ExecutionCount] bigint NULL,
    [AvgDurationMs] decimal(18,2) NULL,
    [AvgCPUTimeMs] decimal(18,2) NULL,
    [AvgLogicalReads] decimal(18,2) NULL,
    [AvgPhysicalReads] decimal(18,2) NULL,
    [CollectedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [perf].[QueryStoreMetrics]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'perf' AND TABLE_NAME = 'StatisticsHealth')
BEGIN
    CREATE TABLE [perf].[StatisticsHealth] (
    [StatHealthID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [TableName] nvarchar(512) NOT NULL,
    [StatisticsName] nvarchar(512) NOT NULL,
    [LastUpdated] datetime2 NULL,
    [RowsModified] bigint NULL,
    [ModificationPercent] decimal(5,2) NULL,
    [IsStale] bit NULL,
    [CollectedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [perf].[StatisticsHealth]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'perf' AND TABLE_NAME = 'TopQueries')
BEGIN
    CREATE TABLE [perf].[TopQueries] (
    [TopQueryID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [QueryHash] varbinary NULL,
    [QueryText] nvarchar(MAX) NULL,
    [ExecutionCount] bigint NULL,
    [TotalWorkerTimeMs] bigint NULL,
    [TotalElapsedTimeMs] bigint NULL,
    [TotalLogicalReads] bigint NULL,
    [RankByCPU] int NULL,
    [RankByReads] int NULL,
    [CollectedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [perf].[TopQueries]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'perf' AND TABLE_NAME = 'WaitStatistics')
BEGIN
    CREATE TABLE [perf].[WaitStatistics] (
    [WaitStatID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [WaitType] nvarchar(256) NOT NULL,
    [WaitCategory] nvarchar(100) NULL,
    [WaitingTasksCount] bigint NULL,
    [WaitTimeMs] bigint NULL,
    [SignalWaitTimeMs] bigint NULL,
    [CollectedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [perf].[WaitStatistics]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'perf' AND TABLE_NAME = 'WaitTypeReference')
BEGIN
    CREATE TABLE [perf].[WaitTypeReference] (
    [WaitType] nvarchar(256) NOT NULL,
    [WaitCategory] nvarchar(100) NOT NULL,
    [Description] nvarchar(1000) NULL,
    [IsBenign] bit NOT NULL DEFAULT ((0)),
    [RecommendedAction] nvarchar(1000) NULL
    );
    PRINT 'Created [perf].[WaitTypeReference]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'performance' AND TABLE_NAME = 'IndexMaintenance')
BEGIN
    CREATE TABLE [performance].[IndexMaintenance] (
    [IndexMaintenanceID] bigint NOT NULL IDENTITY(1,1),
    [ServerID] int NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [SchemaName] nvarchar(256) NOT NULL,
    [TableName] nvarchar(256) NOT NULL,
    [IndexName] nvarchar(256) NOT NULL,
    [FragmentationPercent] decimal(5,2) NULL,
    [PageCount] bigint NULL,
    [RecommendedAction] nvarchar(40) NULL,
    [CollectedDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [performance].[IndexMaintenance]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'performance' AND TABLE_NAME = 'PLETrending')
BEGIN
    CREATE TABLE [performance].[PLETrending] (
    [PLEID] bigint NOT NULL IDENTITY(1,1),
    [ServerID] int NOT NULL,
    [PLESeconds] int NOT NULL,
    [TargetServerMemoryMB] bigint NULL,
    [TotalServerMemoryMB] bigint NULL,
    [CollectedDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [performance].[PLETrending]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'performance' AND TABLE_NAME = 'StatisticsMaintenance')
BEGIN
    CREATE TABLE [performance].[StatisticsMaintenance] (
    [StatID] bigint NOT NULL IDENTITY(1,1),
    [ServerID] int NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [TableName] nvarchar(256) NOT NULL,
    [StatisticsName] nvarchar(256) NOT NULL,
    [LastUpdated] datetime NULL,
    [ModificationCounter] bigint NULL,
    [CollectedDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [performance].[StatisticsMaintenance]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'performance' AND TABLE_NAME = 'WaitStatsTrending')
BEGIN
    CREATE TABLE [performance].[WaitStatsTrending] (
    [WaitStatsID] bigint NOT NULL IDENTITY(1,1),
    [ServerID] int NOT NULL,
    [WaitType] nvarchar(120) NOT NULL,
    [WaitTimeMS] bigint NULL,
    [WaitCategory] nvarchar(100) NULL,
    [CollectedDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [performance].[WaitStatsTrending]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'pipeline' AND TABLE_NAME = 'DeploymentApproval')
BEGIN
    CREATE TABLE [pipeline].[DeploymentApproval] (
    [ApprovalId] int NOT NULL IDENTITY(1,1),
    [DeploymentId] varchar(50) NOT NULL,
    [RequestedBy] nvarchar(256) NOT NULL,
    [RequestedAt] datetime2 NOT NULL DEFAULT (getdate()),
    [ApprovedBy] nvarchar(256) NULL,
    [ApprovedAt] datetime2 NULL,
    [Status] varchar(20) NOT NULL,
    [Comments] nvarchar(MAX) NULL,
    [ExpiresAt] datetime2 NOT NULL
    );
    PRINT 'Created [pipeline].[DeploymentApproval]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'pipeline' AND TABLE_NAME = 'DeploymentHistory')
BEGIN
    CREATE TABLE [pipeline].[DeploymentHistory] (
    [DeploymentHistoryId] int NOT NULL IDENTITY(1,1),
    [DeploymentId] varchar(50) NOT NULL,
    [ScriptPath] nvarchar(1000) NOT NULL,
    [SqlInstance] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [Environment] varchar(10) NOT NULL,
    [Status] varchar(20) NOT NULL,
    [StartTime] datetime2 NOT NULL,
    [EndTime] datetime2 NULL,
    [DurationSeconds] int NULL,
    [BackupPath] nvarchar(1000) NULL,
    [ScriptsExecuted] int NULL DEFAULT ((0)),
    [ErrorMessage] nvarchar(MAX) NULL,
    [WarningMessage] nvarchar(MAX) NULL,
    [DeployedBy] nvarchar(256) NOT NULL DEFAULT (suser_sname()),
    [TicketNumber] varchar(50) NULL,
    [CreatedAt] datetime2 NOT NULL DEFAULT (getdate())
    );
    PRINT 'Created [pipeline].[DeploymentHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'pipeline' AND TABLE_NAME = 'DeploymentLog')
BEGIN
    CREATE TABLE [pipeline].[DeploymentLog] (
    [DeploymentLogId] int NOT NULL IDENTITY(1,1),
    [DeploymentId] varchar(50) NOT NULL,
    [LogTime] datetime2 NOT NULL DEFAULT (getdate()),
    [LogLevel] varchar(20) NOT NULL,
    [Message] nvarchar(MAX) NOT NULL
    );
    PRINT 'Created [pipeline].[DeploymentLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'pipeline' AND TABLE_NAME = 'EnvironmentConfig')
BEGIN
    CREATE TABLE [pipeline].[EnvironmentConfig] (
    [EnvironmentConfigId] int NOT NULL IDENTITY(1,1),
    [Environment] varchar(10) NOT NULL,
    [SqlInstance] nvarchar(256) NOT NULL,
    [DefaultDatabase] nvarchar(256) NULL,
    [RequiresApproval] bit NOT NULL DEFAULT ((0)),
    [AutoBackup] bit NOT NULL DEFAULT ((1)),
    [ApproverGroup] nvarchar(512) NULL,
    [NotificationEmail] nvarchar(512) NULL,
    [IsActive] bit NOT NULL DEFAULT ((1)),
    [CreatedAt] datetime2 NOT NULL DEFAULT (getdate()),
    [ModifiedAt] datetime2 NULL
    );
    PRINT 'Created [pipeline].[EnvironmentConfig]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'playbook' AND TABLE_NAME = 'Categories')
BEGIN
    CREATE TABLE [playbook].[Categories] (
    [CategoryID] int NOT NULL IDENTITY(1,1),
    [CategoryName] nvarchar(200) NOT NULL,
    [Description] nvarchar(1000) NULL,
    [Icon] nvarchar(100) NULL,
    [SortOrder] int NULL DEFAULT ((100))
    );
    PRINT 'Created [playbook].[Categories]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'playbook' AND TABLE_NAME = 'Checkpoints')
BEGIN
    CREATE TABLE [playbook].[Checkpoints] (
    [CheckpointID] bigint NOT NULL IDENTITY(1,1),
    [ExecutionID] bigint NOT NULL,
    [StepID] int NOT NULL,
    [ServerName] nvarchar(256) NULL,
    [CheckpointData] nvarchar(MAX) NULL,
    [CreatedDate] datetime2 NULL DEFAULT (getdate()),
    [RestoredDate] datetime2 NULL,
    [RestoredBy] nvarchar(200) NULL
    );
    PRINT 'Created [playbook].[Checkpoints]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'playbook' AND TABLE_NAME = 'ExecutionHistory')
BEGIN
    CREATE TABLE [playbook].[ExecutionHistory] (
    [ExecutionID] bigint NOT NULL IDENTITY(1,1),
    [PlaybookID] int NOT NULL,
    [IncidentID] bigint NULL,
    [ServerName] nvarchar(256) NULL,
    [CMSGroupName] nvarchar(400) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [StartedDate] datetime2 NULL DEFAULT (getdate()),
    [CompletedDate] datetime2 NULL,
    [ExecutedBy] nvarchar(200) NULL DEFAULT (suser_sname()),
    [ApprovedBy] nvarchar(200) NULL,
    [ApprovalDate] datetime2 NULL,
    [Status] nvarchar(100) NULL DEFAULT ('Running'),
    [CurrentStepNumber] int NULL DEFAULT ((1)),
    [LastError] nvarchar(MAX) NULL,
    [ResultSummary] nvarchar(MAX) NULL,
    [TrackITTicket] nvarchar(100) NULL,
    [ChangeControlNumber] nvarchar(100) NULL
    );
    PRINT 'Created [playbook].[ExecutionHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'playbook' AND TABLE_NAME = 'Playbooks')
BEGIN
    CREATE TABLE [playbook].[Playbooks] (
    [PlaybookID] int NOT NULL IDENTITY(1,1),
    [PlaybookCode] nvarchar(100) NOT NULL,
    [PlaybookName] nvarchar(400) NOT NULL,
    [Description] nvarchar(MAX) NULL,
    [CategoryID] int NULL,
    [OverallRiskLevel] int NULL,
    [TriggerAlertTypes] nvarchar(1000) NULL,
    [TriggerThreshold] nvarchar(400) NULL,
    [EstimatedMinutes] int NULL DEFAULT ((15)),
    [AllowedCMSGroups] nvarchar(1000) NULL,
    [RequiresCJISApproval] bit NULL DEFAULT ((0)),
    [PrerequisitePlaybookID] int NULL,
    [IsActive] bit NULL DEFAULT ((1)),
    [CreatedDate] datetime2 NULL DEFAULT (getdate()),
    [CreatedBy] nvarchar(200) NULL DEFAULT (suser_sname()),
    [ModifiedDate] datetime2 NULL DEFAULT (getdate()),
    [Version] nvarchar(40) NULL DEFAULT ('1.0.0'),
    [Tags] nvarchar(1000) NULL
    );
    PRINT 'Created [playbook].[Playbooks]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'playbook' AND TABLE_NAME = 'RiskLevels')
BEGIN
    CREATE TABLE [playbook].[RiskLevels] (
    [RiskLevelID] int NOT NULL,
    [RiskName] nvarchar(100) NOT NULL,
    [Description] nvarchar(1000) NULL,
    [Color] nvarchar(40) NULL,
    [RequiresApproval] bit NULL DEFAULT ((0)),
    [RequiresCheckpoint] bit NULL DEFAULT ((0)),
    [AllowedCMSGroups] nvarchar(1000) NULL
    );
    PRINT 'Created [playbook].[RiskLevels]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'playbook' AND TABLE_NAME = 'StepExecution')
BEGIN
    CREATE TABLE [playbook].[StepExecution] (
    [StepExecutionID] bigint NOT NULL IDENTITY(1,1),
    [ExecutionID] bigint NOT NULL,
    [StepID] int NOT NULL,
    [StepNumber] int NOT NULL,
    [StartedDate] datetime2 NULL DEFAULT (getdate()),
    [CompletedDate] datetime2 NULL,
    [Status] nvarchar(100) NULL DEFAULT ('Pending'),
    [Output] nvarchar(MAX) NULL,
    [ErrorMessage] nvarchar(MAX) NULL,
    [DurationSeconds] int NULL
    );
    PRINT 'Created [playbook].[StepExecution]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'playbook' AND TABLE_NAME = 'Steps')
BEGIN
    CREATE TABLE [playbook].[Steps] (
    [StepID] int NOT NULL IDENTITY(1,1),
    [PlaybookID] int NOT NULL,
    [StepNumber] int NOT NULL,
    [StepTitle] nvarchar(400) NOT NULL,
    [StepDescription] nvarchar(MAX) NULL,
    [StepType] nvarchar(100) NOT NULL,
    [RiskLevel] int NULL,
    [ScriptType] nvarchar(100) NULL,
    [Script] nvarchar(MAX) NULL,
    [ExpectedOutcome] nvarchar(1000) NULL,
    [SuccessCriteria] nvarchar(1000) NULL,
    [RollbackScript] nvarchar(MAX) NULL,
    [TimeoutSeconds] int NULL DEFAULT ((300)),
    [ContinueOnFailure] bit NULL DEFAULT ((0)),
    [RequiresConfirmation] bit NULL DEFAULT ((0)),
    [ConfirmationPrompt] nvarchar(1000) NULL,
    [NextStepOnSuccess] int NULL,
    [NextStepOnFailure] int NULL
    );
    PRINT 'Created [playbook].[Steps]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'repl' AND TABLE_NAME = 'DistributionHealth')
BEGIN
    CREATE TABLE [repl].[DistributionHealth] (
    [HealthID] bigint NOT NULL IDENTITY(1,1),
    [DistributorServer] nvarchar(256) NOT NULL,
    [DistributionDB] nvarchar(256) NOT NULL,
    [TotalTransactions] bigint NULL,
    [UndeliveredCommands] bigint NULL,
    [OldestTransactionAgeHours] int NULL,
    [DatabaseSizeMB] decimal(18,2) NULL,
    [Status] nvarchar(100) NULL,
    [CollectedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [repl].[DistributionHealth]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'repl' AND TABLE_NAME = 'PerformanceMetrics')
BEGIN
    CREATE TABLE [repl].[PerformanceMetrics] (
    [MetricID] bigint NOT NULL IDENTITY(1,1),
    [PublicationID] int NOT NULL,
    [UndeliveredCommandsCount] bigint NULL,
    [DeliveryRateCommandsPerSec] decimal(18,2) NULL,
    [DistributorLatencySeconds] int NULL,
    [CollectedDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [repl].[PerformanceMetrics]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'repl' AND TABLE_NAME = 'Publications')
BEGIN
    CREATE TABLE [repl].[Publications] (
    [PublicationID] int NOT NULL IDENTITY(1,1),
    [PublisherID] int NOT NULL,
    [PublicationName] nvarchar(256) NOT NULL,
    [PublicationDB] nvarchar(256) NOT NULL,
    [PublicationType] nvarchar(120) NULL,
    [Status] tinyint NULL,
    [CollectedDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [repl].[Publications]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'repl' AND TABLE_NAME = 'Publishers')
BEGIN
    CREATE TABLE [repl].[Publishers] (
    [PublisherID] int NOT NULL IDENTITY(1,1),
    [ServerID] int NOT NULL,
    [PublisherName] nvarchar(256) NOT NULL,
    [DistributorName] nvarchar(256) NULL,
    [DistributionDB] nvarchar(256) NULL,
    [WorkingDirectory] nvarchar(1000) NULL,
    [IsDistributor] bit NOT NULL DEFAULT ((0)),
    [CollectedDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [repl].[Publishers]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'repl' AND TABLE_NAME = 'ReplicationAgentStatus')
BEGIN
    CREATE TABLE [repl].[ReplicationAgentStatus] (
    [AgentStatusID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [AgentType] nvarchar(100) NOT NULL,
    [AgentName] nvarchar(512) NOT NULL,
    [Status] nvarchar(100) NOT NULL,
    [LastActionTime] datetime2 NULL,
    [LastAction] nvarchar(1000) NULL,
    [ErrorMessage] nvarchar(MAX) NULL,
    [CollectedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [repl].[ReplicationAgentStatus]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'repl' AND TABLE_NAME = 'ReplicationLatencyHistory')
BEGIN
    CREATE TABLE [repl].[ReplicationLatencyHistory] (
    [LatencyID] bigint NOT NULL IDENTITY(1,1),
    [PublisherServer] nvarchar(256) NOT NULL,
    [PublicationName] nvarchar(512) NOT NULL,
    [SubscriberServer] nvarchar(256) NOT NULL,
    [SubscriberDB] nvarchar(256) NOT NULL,
    [LatencySeconds] int NOT NULL,
    [PendingCommands] bigint NULL,
    [Status] nvarchar(100) NULL,
    [CollectedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [repl].[ReplicationLatencyHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'repl' AND TABLE_NAME = 'ReplicationPublishers')
BEGIN
    CREATE TABLE [repl].[ReplicationPublishers] (
    [PublisherID] int NOT NULL IDENTITY(1,1),
    [PublisherServer] nvarchar(256) NOT NULL,
    [DistributorServer] nvarchar(256) NULL,
    [PublicationDB] nvarchar(256) NOT NULL,
    [PublicationName] nvarchar(512) NOT NULL,
    [PublicationType] nvarchar(100) NULL,
    [ArticleCount] int NULL,
    [SubscriberCount] int NULL,
    [LastChecked] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [IsActive] bit NOT NULL DEFAULT ((1))
    );
    PRINT 'Created [repl].[ReplicationPublishers]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'repl' AND TABLE_NAME = 'ReplicationSubscribers')
BEGIN
    CREATE TABLE [repl].[ReplicationSubscribers] (
    [SubscriberID] int NOT NULL IDENTITY(1,1),
    [PublisherID] int NOT NULL,
    [SubscriberServer] nvarchar(256) NOT NULL,
    [SubscriberDB] nvarchar(256) NOT NULL,
    [SubscriptionType] nvarchar(100) NULL,
    [Status] nvarchar(100) NULL,
    [LastSyncTime] datetime2 NULL,
    [PendingCommands] bigint NULL,
    [EstimatedLatencySeconds] int NULL,
    [LastChecked] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [repl].[ReplicationSubscribers]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'repl' AND TABLE_NAME = 'Subscriptions')
BEGIN
    CREATE TABLE [repl].[Subscriptions] (
    [SubscriptionID] int NOT NULL IDENTITY(1,1),
    [PublicationID] int NOT NULL,
    [SubscriberServerName] nvarchar(256) NOT NULL,
    [SubscriberDB] nvarchar(256) NOT NULL,
    [SubscriptionType] nvarchar(120) NULL,
    [Status] tinyint NULL,
    [LastSyncTime] datetime NULL,
    [CollectedDate] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [repl].[Subscriptions]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'replmon' AND TABLE_NAME = 'LatencyHistory')
BEGIN
    CREATE TABLE [replmon].[LatencyHistory] (
    [HistoryID] bigint NOT NULL IDENTITY(1,1),
    [PublisherServer] nvarchar(512) NOT NULL,
    [PublisherDB] nvarchar(512) NOT NULL,
    [PublicationName] nvarchar(512) NOT NULL,
    [SubscriberServer] nvarchar(512) NOT NULL,
    [LatencySeconds] int NULL,
    [MeasuredAt] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [replmon].[LatencyHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'replmon' AND TABLE_NAME = 'PublicationStatus')
BEGIN
    CREATE TABLE [replmon].[PublicationStatus] (
    [StatusID] bigint NOT NULL IDENTITY(1,1),
    [PublisherServer] nvarchar(512) NOT NULL,
    [PublisherDB] nvarchar(512) NOT NULL,
    [PublicationName] nvarchar(512) NOT NULL,
    [PublicationType] nvarchar(100) NULL,
    [Status] nvarchar(100) NULL,
    [ArticleCount] int NULL,
    [SubscriptionCount] int NULL,
    [LastSyncTime] datetime NULL,
    [CollectedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [replmon].[PublicationStatus]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'replmon' AND TABLE_NAME = 'SubscriptionStatus')
BEGIN
    CREATE TABLE [replmon].[SubscriptionStatus] (
    [StatusID] bigint NOT NULL IDENTITY(1,1),
    [PublisherServer] nvarchar(512) NOT NULL,
    [PublisherDB] nvarchar(512) NOT NULL,
    [PublicationName] nvarchar(512) NOT NULL,
    [SubscriberServer] nvarchar(512) NOT NULL,
    [SubscriberDB] nvarchar(512) NOT NULL,
    [SubscriptionType] nvarchar(100) NULL,
    [Status] nvarchar(100) NULL,
    [LastSyncTime] datetime NULL,
    [PendingCommands] int NULL,
    [LatencySeconds] int NULL,
    [CollectedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [replmon].[SubscriptionStatus]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'report' AND TABLE_NAME = 'DailyHealthReport')
BEGIN
    CREATE TABLE [report].[DailyHealthReport] (
    [ReportID] int NOT NULL IDENTITY(1,1),
    [ReportDate] date NOT NULL,
    [OverallStatus] nvarchar(40) NOT NULL,
    [HealthScore] int NOT NULL,
    [TotalServers] int NOT NULL,
    [ProdServers] int NOT NULL,
    [NonProdServers] int NOT NULL,
    [ReachableServers] int NOT NULL,
    [UnreachableServers] int NOT NULL,
    [TotalDatabases] int NOT NULL,
    [AvgCPUPercent] decimal(5,2) NULL,
    [AvgMemoryPercent] decimal(5,2) NULL,
    [FailedJobs] int NOT NULL,
    [BackupNonCompliant] int NOT NULL,
    [LowDiskDrives] int NOT NULL,
    [ReplicationIssues] int NOT NULL,
    [CMSSyncPercent] decimal(5,2) NULL,
    [ReportContent] nvarchar(MAX) NULL,
    [GeneratedAt] datetime2 NOT NULL
    );
    PRINT 'Created [report].[DailyHealthReport]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'report' AND TABLE_NAME = 'PatchServicingBaseline')
BEGIN
    CREATE TABLE [report].[PatchServicingBaseline] (
    [VersionYear] int NOT NULL,
    [LatestLevel] nvarchar(40) NOT NULL,
    [LatestCU] int NULL,
    [LatestSP] int NULL,
    [KB] nvarchar(40) NULL,
    [ReleaseDate] date NULL,
    [IsActive] bit NOT NULL DEFAULT ((1)),
    [ModifiedOn] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [report].[PatchServicingBaseline]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'report' AND TABLE_NAME = 'PatchServicingDetail')
BEGIN
    CREATE TABLE [report].[PatchServicingDetail] (
    [RunId] bigint NOT NULL,
    [ServerName] nvarchar(512) NULL,
    [Environment] nvarchar(100) NULL,
    [ComplianceStatus] nvarchar(100) NULL,
    [SQLVersion] nvarchar(200) NULL,
    [CurrentCULevel] nvarchar(100) NULL,
    [VersionYear] int NULL,
    [CUNum] int NULL,
    [SPNum] int NULL,
    [LatestLevel] nvarchar(40) NULL,
    [LatestCU] int NULL,
    [LatestSP] int NULL,
    [LatestKB] nvarchar(40) NULL,
    [LatestReleaseDate] date NULL,
    [ServicingState] nvarchar(100) NULL,
    [LifecycleState] nvarchar(100) NULL,
    [ExtendedSupportEnd] date NULL,
    [DaysToExtEnd] int NULL,
    [UpgradeRecommendation] nvarchar(400) NULL
    );
    PRINT 'Created [report].[PatchServicingDetail]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'report' AND TABLE_NAME = 'PatchServicingSummary')
BEGIN
    CREATE TABLE [report].[PatchServicingSummary] (
    [RunId] bigint NOT NULL IDENTITY(1,1),
    [RunTime] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [TotalInventory] int NOT NULL,
    [MatchedInStatus] int NOT NULL,
    [MissingInStatus] int NOT NULL,
    [MappingsApplied] int NOT NULL,
    [CurrentServers] int NOT NULL,
    [BehindServers] int NOT NULL,
    [OutOfSupportServers] int NOT NULL,
    [ExtendedSupportServers] int NOT NULL,
    [Notes] nvarchar(8000) NULL
    );
    PRINT 'Created [report].[PatchServicingSummary]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'report' AND TABLE_NAME = 'PatchServicingUnmatched')
BEGIN
    CREATE TABLE [report].[PatchServicingUnmatched] (
    [RunId] bigint NOT NULL,
    [InventoryServerRaw] nvarchar(1024) NOT NULL,
    [InventoryServerKey] nvarchar(1024) NOT NULL,
    [StatusJoinKey] nvarchar(1024) NOT NULL,
    [MappingApplied] bit NOT NULL
    );
    PRINT 'Created [report].[PatchServicingUnmatched]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'report' AND TABLE_NAME = 'SecurityReportHistory')
BEGIN
    CREATE TABLE [report].[SecurityReportHistory] (
    [ReportID] bigint NOT NULL IDENTITY(1,1),
    [ReportDate] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [ReportType] nvarchar(100) NOT NULL,
    [OverallScore] int NOT NULL,
    [CJISScore] int NULL,
    [NISTScore] int NULL,
    [DISAScore] int NULL,
    [TotalServers] int NOT NULL,
    [TotalLogins] int NOT NULL,
    [TotalSysAdmins] int NOT NULL,
    [LoginFailures] int NOT NULL,
    [PermissionChanges] int NOT NULL,
    [ServiceAccountEvents] int NOT NULL,
    [CriticalFindings] int NOT NULL,
    [ReportHTML] nvarchar(MAX) NULL
    );
    PRINT 'Created [report].[SecurityReportHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'report' AND TABLE_NAME = 'SqlLifecycle')
BEGIN
    CREATE TABLE [report].[SqlLifecycle] (
    [VersionYear] int NOT NULL,
    [MainstreamEnd] date NULL,
    [ExtendedEnd] date NULL,
    [ModifiedOn] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [report].[SqlLifecycle]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'report' AND TABLE_NAME = 'SqlServicingEmailLog')
BEGIN
    CREATE TABLE [report].[SqlServicingEmailLog] (
    [LogId] bigint NOT NULL IDENTITY(1,1),
    [RunTime] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [SubjectLine] nvarchar(800) NOT NULL,
    [ToList] nvarchar(MAX) NOT NULL,
    [Status] nvarchar(80) NOT NULL,
    [ErrorMessage] nvarchar(MAX) NULL
    );
    PRINT 'Created [report].[SqlServicingEmailLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'schemactl' AND TABLE_NAME = 'MigrationHistory')
BEGIN
    CREATE TABLE [schemactl].[MigrationHistory] (
    [MigrationId] int NOT NULL IDENTITY(1,1),
    [SqlInstance] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [Version] varchar(50) NOT NULL,
    [ScriptName] nvarchar(512) NOT NULL,
    [AppliedAt] datetime2 NOT NULL DEFAULT (getdate()),
    [AppliedBy] nvarchar(256) NOT NULL DEFAULT (suser_sname()),
    [ExecutionTime] int NULL,
    [Checksum] varchar(64) NOT NULL,
    [Status] varchar(20) NOT NULL,
    [Description] nvarchar(MAX) NULL
    );
    PRINT 'Created [schemactl].[MigrationHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'schemactl' AND TABLE_NAME = 'SchemaBaseline')
BEGIN
    CREATE TABLE [schemactl].[SchemaBaseline] (
    [BaselineId] int NOT NULL IDENTITY(1,1),
    [BaselineName] nvarchar(256) NOT NULL,
    [SqlInstance] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [CreatedAt] datetime2 NOT NULL DEFAULT (getdate()),
    [CreatedBy] nvarchar(256) NOT NULL DEFAULT (suser_sname()),
    [TotalObjects] int NOT NULL DEFAULT ((0)),
    [BaselineHash] varchar(64) NOT NULL,
    [FilePath] nvarchar(1000) NOT NULL,
    [Description] nvarchar(MAX) NULL,
    [IsActive] bit NOT NULL DEFAULT ((1))
    );
    PRINT 'Created [schemactl].[SchemaBaseline]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'schemaDoc' AND TABLE_NAME = 'DocumentationLog')
BEGIN
    CREATE TABLE [schemaDoc].[DocumentationLog] (
    [LogID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [GeneratedAt] datetime NOT NULL DEFAULT (getdate()),
    [TableCount] int NULL,
    [ViewCount] int NULL,
    [ProcedureCount] int NULL,
    [FunctionCount] int NULL,
    [ColumnCount] int NULL,
    [RelationshipCount] int NULL,
    [Status] varchar(20) NOT NULL DEFAULT ('Success'),
    [DurationSeconds] int NULL,
    [OutputPath] nvarchar(1000) NULL,
    [ErrorMessage] nvarchar(MAX) NULL,
    [GeneratedBy] nvarchar(256) NULL DEFAULT (suser_sname())
    );
    PRINT 'Created [schemaDoc].[DocumentationLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'sec' AND TABLE_NAME = 'SecurityBaseline')
BEGIN
    CREATE TABLE [sec].[SecurityBaseline] (
    [BaselineID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [LoginName] nvarchar(256) NULL,
    [TypeDesc] nvarchar(128) NULL,
    [DefaultDB] nvarchar(256) NULL,
    [CreateDate] datetime NULL,
    [ModifyDate] datetime NULL,
    [HasSysAdmin] bit NULL,
    [CollectedAt] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [sec].[SecurityBaseline]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'AccessLog')
BEGIN
    CREATE TABLE [security].[AccessLog] (
    [AccessID] bigint NOT NULL IDENTITY(1,1),
    [AccessDate] datetime2 NOT NULL DEFAULT (getdate()),
    [UserName] nvarchar(256) NOT NULL,
    [UserRole] nvarchar(100) NULL,
    [IPAddress] nvarchar(100) NULL,
    [UserAgent] nvarchar(1000) NULL,
    [SessionID] nvarchar(200) NULL,
    [LoginSuccess] bit NOT NULL,
    [FailureReason] nvarchar(1000) NULL
    );
    PRINT 'Created [security].[AccessLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'ADGroupAccessControl')
BEGIN
    CREATE TABLE [security].[ADGroupAccessControl] (
    [AccessControlID] int NOT NULL IDENTITY(1,1),
    [ADGroupName] nvarchar(200) NOT NULL,
    [ADGroupDescription] nvarchar(1000) NULL,
    [ComplianceTier] nvarchar(100) NOT NULL,
    [AccessLevel] nvarchar(100) NOT NULL,
    [RequiresBackground] bit NOT NULL DEFAULT ((0)),
    [RequiresMFA] bit NOT NULL DEFAULT ((0)),
    [CanAccessCJI] bit NOT NULL DEFAULT ((0)),
    [CanAccessPII] bit NOT NULL DEFAULT ((0)),
    [CanModifyData] bit NOT NULL DEFAULT ((0)),
    [CanExecuteCode] bit NOT NULL DEFAULT ((0)),
    [AuditLevel] nvarchar(100) NOT NULL,
    [CreatedDate] datetime2 NULL DEFAULT (sysdatetime()),
    [ModifiedDate] datetime2 NULL DEFAULT (sysdatetime()),
    [Notes] nvarchar(MAX) NULL
    );
    PRINT 'Created [security].[ADGroupAccessControl]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'ADGroups')
BEGIN
    CREATE TABLE [security].[ADGroups] (
    [ADGroupID] int NOT NULL IDENTITY(1,1),
    [ADGroupName] nvarchar(400) NOT NULL,
    [RoleName] varchar(50) NOT NULL,
    [Description] nvarchar(1000) NULL,
    [IsActive] bit NOT NULL DEFAULT ((1)),
    [CreatedDate] datetime2 NOT NULL DEFAULT (getdate()),
    [ModifiedDate] datetime2 NULL,
    [AccessLevel] varchar(50) NULL,
    [RequiresBackgroundCheck] bit NULL DEFAULT ((0)),
    [RequiresMFA] bit NULL DEFAULT ((0)),
    [CanAccessCJI] bit NULL DEFAULT ((0)),
    [CanAccessPII] bit NULL DEFAULT ((0)),
    [CanModifyData] bit NULL DEFAULT ((0))
    );
    PRINT 'Created [security].[ADGroups]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'AuditLog')
BEGIN
    CREATE TABLE [security].[AuditLog] (
    [AuditID] bigint NOT NULL IDENTITY(1,1),
    [ActionDate] datetime2 NOT NULL DEFAULT (getdate()),
    [UserName] nvarchar(256) NOT NULL DEFAULT (suser_sname()),
    [UserRole] nvarchar(100) NULL,
    [ActionType] nvarchar(100) NOT NULL,
    [ObjectType] nvarchar(100) NULL,
    [ObjectName] nvarchar(512) NULL,
    [ActionDetails] nvarchar(MAX) NULL,
    [IPAddress] nvarchar(100) NULL,
    [ApplicationName] nvarchar(256) NULL DEFAULT (app_name()),
    [IsSuccess] bit NOT NULL DEFAULT ((1)),
    [ErrorMessage] nvarchar(MAX) NULL
    );
    PRINT 'Created [security].[AuditLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'DatabasePermissions')
BEGIN
    CREATE TABLE [security].[DatabasePermissions] (
    [PermissionID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(512) NOT NULL,
    [DatabaseName] nvarchar(512) NOT NULL,
    [PrincipalName] nvarchar(512) NOT NULL,
    [PrincipalType] nvarchar(100) NULL,
    [RoleName] nvarchar(512) NULL,
    [PermissionName] nvarchar(512) NULL,
    [PermissionState] nvarchar(100) NULL,
    [ObjectName] nvarchar(512) NULL,
    [ObjectType] nvarchar(100) NULL,
    [CollectedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [security].[DatabasePermissions]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'DatabasePrincipals_Backup')
BEGIN
    CREATE TABLE [security].[DatabasePrincipals_Backup] (
    [name] sysname NOT NULL,
    [principal_id] int NOT NULL,
    [type] char(1) NOT NULL,
    [type_desc] nvarchar(120) NULL,
    [default_schema_name] sysname NULL,
    [create_date] datetime NOT NULL,
    [modify_date] datetime NOT NULL,
    [owning_principal_id] int NULL,
    [sid] varbinary NULL,
    [is_fixed_role] bit NOT NULL,
    [authentication_type] int NOT NULL,
    [authentication_type_desc] nvarchar(120) NULL,
    [default_language_name] sysname NULL,
    [default_language_lcid] int NULL,
    [allow_encrypted_value_modifications] bit NOT NULL,
    [tenant_id] uniqueidentifier NULL
    );
    PRINT 'Created [security].[DatabasePrincipals_Backup]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'DatabaseUserMapping')
BEGIN
    CREATE TABLE [security].[DatabaseUserMapping] (
    [MappingID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [UserName] nvarchar(256) NULL,
    [LoginName] nvarchar(256) NULL,
    [UserType] nvarchar(120) NULL,
    [DefaultSchema] nvarchar(256) NULL,
    [CreateDate] datetime NULL,
    [ModifyDate] datetime NULL,
    [CollectedAt] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [security].[DatabaseUserMapping]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'DDLAuditLog')
BEGIN
    CREATE TABLE [security].[DDLAuditLog] (
    [AuditID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(512) NOT NULL,
    [DatabaseName] nvarchar(512) NULL,
    [EventType] nvarchar(200) NOT NULL,
    [ObjectName] nvarchar(512) NULL,
    [ObjectType] nvarchar(100) NULL,
    [SchemaName] nvarchar(512) NULL,
    [LoginName] nvarchar(512) NULL,
    [UserName] nvarchar(512) NULL,
    [EventTime] datetime NOT NULL,
    [TSQLCommand] nvarchar(MAX) NULL,
    [CollectedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [security].[DDLAuditLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'ExpectedLocalAdmins')
BEGIN
    CREATE TABLE [security].[ExpectedLocalAdmins] (
    [AdminID] int NOT NULL IDENTITY(1,1),
    [AccountName] varchar(256) NOT NULL,
    [Description] varchar(400) NULL,
    [IsActive] bit NOT NULL DEFAULT ((1)),
    [CreatedDate] datetime NOT NULL DEFAULT (getdate())
    );
    PRINT 'Created [security].[ExpectedLocalAdmins]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'LocalAdminMembership')
BEGIN
    CREATE TABLE [security].[LocalAdminMembership] (
    [RecordID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] varchar(128) NOT NULL,
    [AccountName] varchar(256) NOT NULL,
    [IsExpected] bit NULL,
    [CollectedTime] datetime NOT NULL DEFAULT (getdate()),
    [Source] varchar(50) NOT NULL DEFAULT ('Automated')
    );
    PRINT 'Created [security].[LocalAdminMembership]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'LoginAudit')
BEGIN
    CREATE TABLE [security].[LoginAudit] (
    [AuditID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(512) NOT NULL,
    [LoginName] nvarchar(512) NOT NULL,
    [EventType] nvarchar(100) NULL,
    [EventTime] datetime NOT NULL,
    [ClientHost] nvarchar(512) NULL,
    [ApplicationName] nvarchar(512) NULL,
    [ErrorNumber] int NULL,
    [ErrorMessage] nvarchar(MAX) NULL,
    [CollectedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [security].[LoginAudit]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'LoginAuditHistory')
BEGIN
    CREATE TABLE [security].[LoginAuditHistory] (
    [AuditID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [EventTime] datetime2 NOT NULL,
    [EventType] nvarchar(200) NOT NULL,
    [LoginName] nvarchar(256) NOT NULL,
    [HostName] nvarchar(256) NULL,
    [IPAddress] nvarchar(100) NULL,
    [ApplicationName] nvarchar(512) NULL,
    [IsSuccess] bit NOT NULL,
    [ErrorMessage] nvarchar(1000) NULL,
    [CollectedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [security].[LoginAuditHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'LoginInventory')
BEGIN
    CREATE TABLE [security].[LoginInventory] (
    [LoginID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [LoginName] nvarchar(256) NULL,
    [LoginType] nvarchar(120) NULL,
    [IsDisabled] bit NULL,
    [CreateDate] datetime NULL,
    [ModifyDate] datetime NULL,
    [DefaultDatabase] nvarchar(256) NULL,
    [HasAccess] bit NULL,
    [IsSysAdmin] bit NULL,
    [IsSecurityAdmin] bit NULL,
    [IsServerAdmin] bit NULL,
    [IsSetupAdmin] bit NULL,
    [IsProcessAdmin] bit NULL,
    [IsDiskAdmin] bit NULL,
    [IsBulkAdmin] bit NULL,
    [CollectedAt] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [security].[LoginInventory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'MissingLocalAdminCompliance')
BEGIN
    CREATE TABLE [security].[MissingLocalAdminCompliance] (
    [ComplianceID] int NOT NULL IDENTITY(1,1),
    [ServerName] varchar(200) NULL,
    [RequiredAccount] varchar(200) NULL,
    [CollectedTime] datetime2 NULL,
    [IsMissing] bit NULL,
    [LoggedOn] datetime2 NULL DEFAULT (sysutcdatetime())
    );
    PRINT 'Created [security].[MissingLocalAdminCompliance]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'NotificationLog')
BEGIN
    CREATE TABLE [security].[NotificationLog] (
    [LogID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [AlertSeverity] varchar(20) NULL,
    [AlertType] varchar(50) NULL,
    [Subject] nvarchar(1000) NULL,
    [Recipients] nvarchar(1000) NULL,
    [MailProfile] nvarchar(400) NULL,
    [SentDate] datetime2 NOT NULL DEFAULT (getdate()),
    [MailItemID] int NULL,
    [SendStatus] varchar(500) NULL
    );
    PRINT 'Created [security].[NotificationLog]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'NotificationPreferences')
BEGIN
    CREATE TABLE [security].[NotificationPreferences] (
    [PreferenceID] int NOT NULL IDENTITY(1,1),
    [RoleName] varchar(50) NOT NULL,
    [AlertSeverity] varchar(20) NOT NULL,
    [MailProfile] nvarchar(400) NOT NULL,
    [RecipientEmail] nvarchar(400) NULL,
    [IsEnabled] bit NOT NULL DEFAULT ((1)),
    [CreatedDate] datetime2 NOT NULL DEFAULT (getdate())
    );
    PRINT 'Created [security].[NotificationPreferences]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'ObjectPermissions')
BEGIN
    CREATE TABLE [security].[ObjectPermissions] (
    [PermissionID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [PrincipalName] nvarchar(256) NULL,
    [PrincipalType] nvarchar(120) NULL,
    [ObjectSchema] nvarchar(256) NULL,
    [ObjectName] nvarchar(256) NULL,
    [ObjectType] nvarchar(120) NULL,
    [PermissionName] nvarchar(256) NULL,
    [PermissionState] nvarchar(120) NULL,
    [CollectedAt] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [security].[ObjectPermissions]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'Operators_Backup')
BEGIN
    CREATE TABLE [security].[Operators_Backup] (
    [id] int NOT NULL IDENTITY(1,1),
    [name] sysname NOT NULL,
    [enabled] tinyint NOT NULL,
    [email_address] nvarchar(200) NULL,
    [last_email_date] int NOT NULL,
    [last_email_time] int NOT NULL,
    [pager_address] nvarchar(200) NULL,
    [last_pager_date] int NOT NULL,
    [last_pager_time] int NOT NULL,
    [weekday_pager_start_time] int NOT NULL,
    [weekday_pager_end_time] int NOT NULL,
    [saturday_pager_start_time] int NOT NULL,
    [saturday_pager_end_time] int NOT NULL,
    [sunday_pager_start_time] int NOT NULL,
    [sunday_pager_end_time] int NOT NULL,
    [pager_days] tinyint NOT NULL,
    [netsend_address] nvarchar(200) NULL,
    [last_netsend_date] int NOT NULL,
    [last_netsend_time] int NOT NULL,
    [category_id] int NOT NULL
    );
    PRINT 'Created [security].[Operators_Backup]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'OrphanedUsers')
BEGIN
    CREATE TABLE [security].[OrphanedUsers] (
    [OrphanedUserID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [UserName] nvarchar(256) NOT NULL,
    [DetectedAt] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [IsResolved] bit NOT NULL DEFAULT ((0)),
    [ResolvedAt] datetime2 NULL
    );
    PRINT 'Created [security].[OrphanedUsers]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'PermissionBaseline')
BEGIN
    CREATE TABLE [security].[PermissionBaseline] (
    [BaselineID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(512) NOT NULL,
    [DatabaseName] nvarchar(512) NULL,
    [PrincipalName] nvarchar(512) NOT NULL,
    [PermissionName] nvarchar(512) NOT NULL,
    [PermissionScope] nvarchar(100) NULL,
    [ObjectName] nvarchar(512) NULL,
    [IsApproved] bit NULL DEFAULT ((1)),
    [ApprovedBy] nvarchar(512) NULL,
    [ApprovedDate] datetime NULL DEFAULT (getdate()),
    [Notes] nvarchar(MAX) NULL
    );
    PRINT 'Created [security].[PermissionBaseline]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'PermissionChanges')
BEGIN
    CREATE TABLE [security].[PermissionChanges] (
    [ChangeID] bigint NOT NULL IDENTITY(1,1),
    [ChangeDate] datetime2 NOT NULL DEFAULT (getdate()),
    [ChangedBy] nvarchar(256) NOT NULL DEFAULT (suser_sname()),
    [ChangeType] nvarchar(100) NOT NULL,
    [PrincipalName] nvarchar(256) NOT NULL,
    [ObjectType] nvarchar(100) NULL,
    [ObjectName] nvarchar(512) NULL,
    [Permission] nvarchar(256) NULL,
    [OldValue] nvarchar(MAX) NULL,
    [NewValue] nvarchar(MAX) NULL,
    [Justification] nvarchar(MAX) NULL
    );
    PRINT 'Created [security].[PermissionChanges]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'PermissionDrift')
BEGIN
    CREATE TABLE [security].[PermissionDrift] (
    [DriftID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(512) NOT NULL,
    [DatabaseName] nvarchar(512) NULL,
    [PrincipalName] nvarchar(512) NOT NULL,
    [PermissionName] nvarchar(512) NOT NULL,
    [DriftType] nvarchar(100) NULL,
    [DetectedDate] datetime NULL DEFAULT (getdate()),
    [IsResolved] bit NULL DEFAULT ((0)),
    [ResolvedDate] datetime NULL,
    [ResolvedBy] nvarchar(512) NULL,
    [Notes] nvarchar(MAX) NULL
    );
    PRINT 'Created [security].[PermissionDrift]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'PolicyViolations')
BEGIN
    CREATE TABLE [security].[PolicyViolations] (
    [ViolationID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NULL,
    [PolicyName] nvarchar(400) NOT NULL,
    [ViolationDetail] nvarchar(MAX) NULL,
    [Severity] nvarchar(40) NOT NULL,
    [DetectedAt] datetime2 NOT NULL DEFAULT (sysdatetime()),
    [Status] nvarchar(100) NOT NULL DEFAULT ('Open'),
    [RemediatedAt] datetime2 NULL
    );
    PRINT 'Created [security].[PolicyViolations]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'RequiredLocalAdmins')
BEGIN
    CREATE TABLE [security].[RequiredLocalAdmins] (
    [AdminID] int NOT NULL IDENTITY(1,1),
    [AccountName] nvarchar(510) NOT NULL,
    [IsMandatory] bit NOT NULL DEFAULT ((1)),
    [AddedOn] datetime NOT NULL DEFAULT (getdate())
    );
    PRINT 'Created [security].[RequiredLocalAdmins]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'RoleMembership')
BEGIN
    CREATE TABLE [security].[RoleMembership] (
    [MembershipID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NULL,
    [DatabaseName] nvarchar(256) NULL,
    [RoleName] nvarchar(256) NULL,
    [MemberName] nvarchar(256) NULL,
    [MemberType] nvarchar(120) NULL,
    [RoleType] nvarchar(40) NULL,
    [CollectedAt] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [security].[RoleMembership]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'ServerPermissions')
BEGIN
    CREATE TABLE [security].[ServerPermissions] (
    [PermissionID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(512) NOT NULL,
    [PrincipalName] nvarchar(512) NOT NULL,
    [PrincipalType] nvarchar(100) NULL,
    [PermissionName] nvarchar(512) NOT NULL,
    [PermissionState] nvarchar(100) NULL,
    [CollectedDate] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [security].[ServerPermissions]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'ServerPrincipals_Backup')
BEGIN
    CREATE TABLE [security].[ServerPrincipals_Backup] (
    [name] sysname NOT NULL,
    [principal_id] int NOT NULL,
    [sid] varbinary NULL,
    [type] char(1) NOT NULL,
    [type_desc] nvarchar(120) NULL,
    [is_disabled] bit NULL,
    [create_date] datetime NOT NULL,
    [modify_date] datetime NOT NULL,
    [default_database_name] sysname NULL,
    [default_language_name] sysname NULL,
    [credential_id] int NULL,
    [owning_principal_id] int NULL,
    [is_fixed_role] bit NOT NULL,
    [tenant_id] uniqueidentifier NULL
    );
    PRINT 'Created [security].[ServerPrincipals_Backup]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'ServerRoleMapping')
BEGIN
    CREATE TABLE [security].[ServerRoleMapping] (
    [MappingID] int NOT NULL IDENTITY(1,1),
    [ComplianceTier] varchar(100) NOT NULL,
    [ADGroupName] nvarchar(256) NOT NULL,
    [DesiredServerRole] nvarchar(256) NOT NULL,
    [GrantViewServerState] bit NULL DEFAULT ((0)),
    [Notes] nvarchar(1000) NULL
    );
    PRINT 'Created [security].[ServerRoleMapping]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'ServiceAccounts')
BEGIN
    CREATE TABLE [security].[ServiceAccounts] (
    [AccountID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(512) NOT NULL,
    [ServiceName] nvarchar(512) NOT NULL,
    [AccountName] nvarchar(512) NOT NULL,
    [AccountType] nvarchar(100) NULL,
    [StartupType] nvarchar(100) NULL,
    [Status] nvarchar(100) NULL,
    [LastUpdated] datetime NULL DEFAULT (getdate())
    );
    PRINT 'Created [security].[ServiceAccounts]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'SysadminMembership')
BEGIN
    CREATE TABLE [security].[SysadminMembership] (
    [MembershipID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [LoginName] nvarchar(256) NOT NULL,
    [LoginType] nvarchar(120) NULL,
    [IsDisabled] bit NULL,
    [CollectedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [security].[SysadminMembership]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'TDEStatus')
BEGIN
    CREATE TABLE [security].[TDEStatus] (
    [TDEStatusID] bigint NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NOT NULL,
    [EncryptionState] tinyint NULL,
    [EncryptionStateName] nvarchar(100) NULL,
    [CertificateName] nvarchar(512) NULL,
    [CertificateExpiry] datetime2 NULL,
    [CollectedAt] datetime2 NOT NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [security].[TDEStatus]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'stg' AND TABLE_NAME = 'VeeamBackups_Staging')
BEGIN
    CREATE TABLE [stg].[VeeamBackups_Staging] (
    [StagingID] int NOT NULL IDENTITY(1,1),
    [JobName] nvarchar(510) NULL,
    [JobType] nvarchar(200) NULL,
    [BackupType] nvarchar(200) NULL,
    [Progress] int NULL,
    [Status] nvarchar(200) NULL,
    [StartTimeRaw] nvarchar(200) NULL,
    [EndTimeRaw] nvarchar(200) NULL,
    [Result] nvarchar(200) NULL,
    [LoadedAt] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [stg].[VeeamBackups_Staging]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TrackIT' AND TABLE_NAME = 'AlertConfiguration')
BEGIN
    CREATE TABLE [TrackIT].[AlertConfiguration] (
    [AlertID] int NOT NULL IDENTITY(1,1),
    [AlertName] nvarchar(400) NOT NULL,
    [AlertCategory] nvarchar(200) NULL,
    [Severity] nvarchar(40) NULL,
    [EmailRecipients] nvarchar(MAX) NULL,
    [EmailSubjectTemplate] nvarchar(1000) NULL,
    [EmailBodyTemplate] nvarchar(MAX) NULL,
    [IsEnabled] bit NULL DEFAULT ((1)),
    [ThrottleMinutes] int NULL DEFAULT ((60)),
    [CreatedDate] datetime2 NULL DEFAULT (getdate()),
    [ModifiedDate] datetime2 NULL DEFAULT (getdate())
    );
    PRINT 'Created [TrackIT].[AlertConfiguration]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TrackIT' AND TABLE_NAME = 'AlertHistory')
BEGIN
    CREATE TABLE [TrackIT].[AlertHistory] (
    [AlertHistoryID] bigint NOT NULL IDENTITY(1,1),
    [AlertDateTime] datetime2 NULL DEFAULT (getdate()),
    [AlertName] nvarchar(400) NULL,
    [Severity] nvarchar(40) NULL,
    [SourceTable] nvarchar(400) NULL,
    [SourceID] bigint NULL,
    [AlertMessage] nvarchar(MAX) NULL,
    [EmailSent] bit NULL DEFAULT ((0)),
    [EmailSentDateTime] datetime2 NULL,
    [EmailRecipients] nvarchar(MAX) NULL,
    [Acknowledged] bit NULL DEFAULT ((0)),
    [AcknowledgedBy] nvarchar(200) NULL,
    [AcknowledgedDateTime] datetime2 NULL,
    [ResolutionNotes] nvarchar(MAX) NULL
    );
    PRINT 'Created [TrackIT].[AlertHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TrackIT' AND TABLE_NAME = 'ApplicationDependencyHealth')
BEGIN
    CREATE TABLE [TrackIT].[ApplicationDependencyHealth] (
    [DependencyID] bigint NOT NULL IDENTITY(1,1),
    [CheckDateTime] datetime2 NULL DEFAULT (getdate()),
    [AppServiceName] nvarchar(200) NULL,
    [AppServiceState] nvarchar(100) NULL,
    [AppServiceStatus] nvarchar(40) NULL,
    [DBConnectionTime_MS] int NULL,
    [DBConnectionStatus] nvarchar(40) NULL,
    [ConnectionPoolSize] int NULL,
    [ConnectionPoolMax] int NULL,
    [ConnectionPoolStatus] nvarchar(40) NULL,
    [LinkedServerName] nvarchar(256) NULL,
    [LinkedServerResponseTime_MS] int NULL,
    [LinkedServerStatus] nvarchar(40) NULL,
    [AgentJobName] nvarchar(512) NULL,
    [AgentJobLastRunStatus] nvarchar(100) NULL,
    [AgentJobStatus] nvarchar(40) NULL,
    [OverallDependencyStatus] nvarchar(40) NULL,
    [AlertSent] bit NULL DEFAULT ((0))
    );
    PRINT 'Created [TrackIT].[ApplicationDependencyHealth]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TrackIT' AND TABLE_NAME = 'BackupRecoverabilityHealth')
BEGIN
    CREATE TABLE [TrackIT].[BackupRecoverabilityHealth] (
    [BackupID] bigint NOT NULL IDENTITY(1,1),
    [CheckDateTime] datetime2 NULL DEFAULT (getdate()),
    [DatabaseName] nvarchar(256) NOT NULL,
    [LastFullBackup] datetime2 NULL,
    [FullBackupAge_Hours] int NULL,
    [FullBackupStatus] nvarchar(40) NULL,
    [LastTLogBackup] datetime2 NULL,
    [TLogBackupAge_Minutes] int NULL,
    [TLogBackupStatus] nvarchar(40) NULL,
    [LogChainStatus] nvarchar(100) NULL,
    [LogChainHealth] nvarchar(40) NULL,
    [VeeamLastBackup] datetime2 NULL,
    [VeeamBackupStatus] nvarchar(100) NULL,
    [VeeamBackupHealth] nvarchar(40) NULL,
    [RestorePointCount] int NULL,
    [RestorePointCompliance] bit NULL,
    [RestorePointStatus] nvarchar(40) NULL,
    [PointInTimeRecoverable] bit NULL DEFAULT ((1)),
    [OverallBackupStatus] nvarchar(40) NULL,
    [AlertSent] bit NULL DEFAULT ((0)),
    [Notes] nvarchar(MAX) NULL
    );
    PRINT 'Created [TrackIT].[BackupRecoverabilityHealth]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TrackIT' AND TABLE_NAME = 'DatabaseHealthHistory')
BEGIN
    CREATE TABLE [TrackIT].[DatabaseHealthHistory] (
    [HealthID] bigint NOT NULL IDENTITY(1,1),
    [CheckDateTime] datetime2 NULL DEFAULT (getdate()),
    [DatabaseName] nvarchar(256) NOT NULL,
    [DatabaseState] nvarchar(100) NULL,
    [DatabaseStateStatus] nvarchar(40) NULL,
    [SchemaVersion] nvarchar(100) NULL,
    [SchemaChangeDetected] bit NULL DEFAULT ((0)),
    [SchemaChangeType] nvarchar(100) NULL,
    [BlockingDuration_Seconds] int NULL,
    [BlockingStatus] nvarchar(40) NULL,
    [LongQueryDuration_Minutes] int NULL,
    [LongQueryStatus] nvarchar(40) NULL,
    [DeadlockCount] int NULL,
    [DeadlockStatus] nvarchar(40) NULL,
    [LogGrowthMB] decimal(18,2) NULL,
    [LogGrowthType] nvarchar(100) NULL,
    [LogGrowthStatus] nvarchar(40) NULL,
    [OverallHealthScore] int NULL,
    [OverallStatus] nvarchar(40) NULL,
    [AlertSent] bit NULL DEFAULT ((0)),
    [Notes] nvarchar(MAX) NULL
    );
    PRINT 'Created [TrackIT].[DatabaseHealthHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TrackIT' AND TABLE_NAME = 'ReplicationHealth')
BEGIN
    CREATE TABLE [TrackIT].[ReplicationHealth] (
    [ReplicationID] bigint NOT NULL IDENTITY(1,1),
    [CheckDateTime] datetime2 NULL DEFAULT (getdate()),
    [PublicationName] nvarchar(512) NULL,
    [SubscriberServer] nvarchar(512) NULL,
    [SubscriberDB] nvarchar(256) NULL,
    [ReplicationLatency_Seconds] int NULL,
    [LatencyStatus] nvarchar(40) NULL,
    [PendingCommands] bigint NULL,
    [PendingCommandsStatus] nvarchar(40) NULL,
    [LogReaderState] nvarchar(100) NULL,
    [LogReaderStatus] nvarchar(40) NULL,
    [DistributionCleanupState] nvarchar(100) NULL,
    [DistributionCleanupStatus] nvarchar(40) NULL,
    [DataTrustRisk] bit NULL DEFAULT ((0)),
    [OverallReplicationStatus] nvarchar(40) NULL,
    [AlertSent] bit NULL DEFAULT ((0)),
    [Notes] nvarchar(MAX) NULL
    );
    PRINT 'Created [TrackIT].[ReplicationHealth]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TrackIT' AND TABLE_NAME = 'SchemaBaseline')
BEGIN
    CREATE TABLE [TrackIT].[SchemaBaseline] (
    [BaselineID] int NOT NULL IDENTITY(1,1),
    [DatabaseName] nvarchar(256) NOT NULL,
    [SchemaVersion] nvarchar(100) NULL,
    [ObjectType] nvarchar(100) NULL,
    [ObjectSchema] nvarchar(256) NULL,
    [ObjectName] nvarchar(512) NULL,
    [ObjectDefinitionHash] varbinary NULL,
    [BaselineDate] datetime2 NULL DEFAULT (getdate()),
    [IsCurrentBaseline] bit NULL DEFAULT ((1)),
    [ApprovedChange] bit NULL DEFAULT ((0)),
    [ChangeDescription] nvarchar(1000) NULL
    );
    PRINT 'Created [TrackIT].[SchemaBaseline]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TrackIT' AND TABLE_NAME = 'ServiceRegistry')
BEGIN
    CREATE TABLE [TrackIT].[ServiceRegistry] (
    [ServiceID] int NOT NULL IDENTITY(1,1),
    [ServiceName] nvarchar(200) NOT NULL,
    [ServiceTier] nvarchar(100) NULL DEFAULT ('Tier-1 Mission-Critical'),
    [DatabaseName] nvarchar(256) NOT NULL,
    [ServerInstance] nvarchar(512) NOT NULL,
    [RiskProfile] nvarchar(100) NULL DEFAULT ('High'),
    [IsCritical] bit NULL DEFAULT ((1)),
    [IsActive] bit NULL DEFAULT ((1)),
    [CreatedDate] datetime2 NULL DEFAULT (getdate()),
    [ModifiedDate] datetime2 NULL DEFAULT (getdate())
    );
    PRINT 'Created [TrackIT].[ServiceRegistry]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TrackIT' AND TABLE_NAME = 'TaniumPatchGovernance')
BEGIN
    CREATE TABLE [TrackIT].[TaniumPatchGovernance] (
    [PatchID] bigint NOT NULL IDENTITY(1,1),
    [CheckDateTime] datetime2 NULL DEFAULT (getdate()),
    [ServerInstance] nvarchar(512) NOT NULL,
    [LastWindowsPatch] datetime2 NULL,
    [WindowsPatchAge_Days] int NULL,
    [WindowsPatchStatus] nvarchar(40) NULL,
    [SQLVersion] nvarchar(200) NULL,
    [SQLCULevel] nvarchar(100) NULL,
    [SQLCUAge] nvarchar(40) NULL,
    [SQLCUStatus] nvarchar(40) NULL,
    [UnplannedReboot] bit NULL DEFAULT ((0)),
    [UnplannedRebootStatus] nvarchar(40) NULL,
    [SQLServiceInterruption] bit NULL DEFAULT ((0)),
    [SQLServiceInterruptionStatus] nvarchar(40) NULL,
    [PatchDuringTrackITActivity] bit NULL DEFAULT ((0)),
    [PatchDuringActivityStatus] nvarchar(40) NULL,
    [DBAOpsCoordinated] bit NULL DEFAULT ((1)),
    [OverallPatchStatus] nvarchar(40) NULL,
    [AlertSent] bit NULL DEFAULT ((0))
    );
    PRINT 'Created [TrackIT].[TaniumPatchGovernance]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TrackIT' AND TABLE_NAME = 'ThresholdConfiguration')
BEGIN
    CREATE TABLE [TrackIT].[ThresholdConfiguration] (
    [ThresholdID] int NOT NULL IDENTITY(1,1),
    [CheckCategory] nvarchar(200) NOT NULL,
    [MetricName] nvarchar(400) NOT NULL,
    [HealthyMin] decimal(18,2) NULL,
    [HealthyMax] decimal(18,2) NULL,
    [WarningMin] decimal(18,2) NULL,
    [WarningMax] decimal(18,2) NULL,
    [CriticalMin] decimal(18,2) NULL,
    [CriticalMax] decimal(18,2) NULL,
    [Unit] nvarchar(100) NULL,
    [IsEnabled] bit NULL DEFAULT ((1)),
    [Notes] nvarchar(1000) NULL,
    [CreatedDate] datetime2 NULL DEFAULT (getdate()),
    [ModifiedDate] datetime2 NULL DEFAULT (getdate())
    );
    PRINT 'Created [TrackIT].[ThresholdConfiguration]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TrackIT' AND TABLE_NAME = 'UpgradeChangeGovernance')
BEGIN
    CREATE TABLE [TrackIT].[UpgradeChangeGovernance] (
    [ChangeID] int NOT NULL IDENTITY(1,1),
    [ChangeDateTime] datetime2 NULL DEFAULT (getdate()),
    [ChangeType] nvarchar(100) NULL,
    [UpgradeWindowStatus] nvarchar(100) NULL,
    [UpgradeWindowHealth] nvarchar(40) NULL,
    [ApprovedBy] nvarchar(200) NULL,
    [ApprovalDate] datetime2 NULL,
    [PreUpgradeBackupExists] bit NULL,
    [PreUpgradeBackupVerified] bit NULL,
    [PreUpgradeBackupStatus] nvarchar(40) NULL,
    [SchemaValidationPassed] bit NULL,
    [SchemaValidationStatus] nvarchar(40) NULL,
    [SchemaValidationNotes] nvarchar(MAX) NULL,
    [PermissionsIntact] bit NULL,
    [PermissionsStatus] nvarchar(40) NULL,
    [PermissionsDrift] nvarchar(MAX) NULL,
    [PostUpgradeHealthCheck] bit NULL DEFAULT ((0)),
    [PostUpgradeHealthStatus] nvarchar(40) NULL,
    [PostUpgradeNotes] nvarchar(MAX) NULL,
    [OverallChangeStatus] nvarchar(40) NULL,
    [AlertSent] bit NULL DEFAULT ((0))
    );
    PRINT 'Created [TrackIT].[UpgradeChangeGovernance]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TRACS' AND TABLE_NAME = 'BlockingHistory')
BEGIN
    CREATE TABLE [TRACS].[BlockingHistory] (
    [BlockingID] bigint NOT NULL IDENTITY(1,1),
    [CaptureTime] datetime2 NULL DEFAULT (sysdatetime()),
    [ServerName] nvarchar(256) NOT NULL,
    [BlockedSPID] int NULL,
    [BlockedLoginName] nvarchar(256) NULL,
    [BlockedHostName] nvarchar(256) NULL,
    [BlockedDatabaseName] nvarchar(256) NULL,
    [BlockedWaitTimeSeconds] int NULL,
    [BlockedWaitResource] nvarchar(512) NULL,
    [BlockedQuery] nvarchar(MAX) NULL,
    [BlockingSPID] int NULL,
    [BlockingLoginName] nvarchar(256) NULL,
    [BlockingHostName] nvarchar(256) NULL,
    [BlockingQuery] nvarchar(MAX) NULL
    );
    PRINT 'Created [TRACS].[BlockingHistory]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TRACS' AND TABLE_NAME = 'MonitoredServers')
BEGIN
    CREATE TABLE [TRACS].[MonitoredServers] (
    [ServerID] int NOT NULL IDENTITY(1,1),
    [ServerName] nvarchar(256) NOT NULL,
    [Environment] nvarchar(100) NULL,
    [Description] nvarchar(1000) NULL,
    [IsActive] bit NULL DEFAULT ((1)),
    [AddedDate] datetime2 NULL DEFAULT (sysdatetime())
    );
    PRINT 'Created [TRACS].[MonitoredServers]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TRACS' AND TABLE_NAME = 'PerformanceSnapshots')
BEGIN
    CREATE TABLE [TRACS].[PerformanceSnapshots] (
    [SnapshotID] bigint NOT NULL IDENTITY(1,1),
    [CaptureTime] datetime2 NULL DEFAULT (sysdatetime()),
    [ServerName] nvarchar(256) NOT NULL,
    [SQLServerCPUPercent] decimal(5,2) NULL,
    [SystemCPUPercent] decimal(5,2) NULL,
    [SystemIdlePercent] decimal(5,2) NULL,
    [TotalMemoryMB] int NULL,
    [AvailableMemoryMB] int NULL,
    [SQLServerMemoryMB] int NULL,
    [MemoryUsedPercent] decimal(5,2) NULL,
    [PageLifeExpectancy] int NULL,
    [BufferCacheHitRatio] decimal(5,2) NULL,
    [AvgDiskReadLatencyMs] decimal(10,2) NULL,
    [AvgDiskWriteLatencyMs] decimal(10,2) NULL,
    [DiskQueueLength] decimal(10,2) NULL,
    [BatchRequestsPerSec] int NULL,
    [TransactionsPerSec] int NULL,
    [ActiveSessions] int NULL,
    [BlockedSessions] int NULL,
    [TopWaitType] nvarchar(200) NULL,
    [TopWaitTimeMs] bigint NULL
    );
    PRINT 'Created [TRACS].[PerformanceSnapshots]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TRACS' AND TABLE_NAME = 'QueryPerformance')
BEGIN
    CREATE TABLE [TRACS].[QueryPerformance] (
    [QueryPerfID] bigint NOT NULL IDENTITY(1,1),
    [CaptureTime] datetime2 NULL DEFAULT (sysdatetime()),
    [ServerName] nvarchar(256) NOT NULL,
    [DatabaseName] nvarchar(256) NULL,
    [QueryHash] binary NULL,
    [QueryPlanHash] binary NULL,
    [ExecutionCount] bigint NULL,
    [TotalCPUTimeMs] decimal(18,2) NULL,
    [AvgCPUTimeMs] decimal(18,2) NULL,
    [TotalDurationMs] decimal(18,2) NULL,
    [AvgDurationMs] decimal(18,2) NULL,
    [TotalLogicalReads] bigint NULL,
    [AvgLogicalReads] bigint NULL,
    [TotalPhysicalReads] bigint NULL,
    [TotalWrites] bigint NULL,
    [QueryText] nvarchar(MAX) NULL
    );
    PRINT 'Created [TRACS].[QueryPerformance]';
END
GO

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TRACS' AND TABLE_NAME = 'WaitStatsHistory')
BEGIN
    CREATE TABLE [TRACS].[WaitStatsHistory] (
    [WaitStatsID] bigint NOT NULL IDENTITY(1,1),
    [CaptureTime] datetime2 NULL DEFAULT (sysdatetime()),
    [ServerName] nvarchar(256) NOT NULL,
    [WaitType] nvarchar(200) NULL,
    [WaitTimeMs] bigint NULL,
    [WaitingTasksCount] bigint NULL,
    [SignalWaitTimeMs] bigint NULL
    );
    PRINT 'Created [TRACS].[WaitStatsHistory]';
END
GO

