-- ============================================================
-- spMonitoring: System health and statistics
-- ============================================================
CREATE OR ALTER PROCEDURE [dbo].[spMonitoring]
    @action VARCHAR(50),
    @rqst   NVARCHAR(MAX),
    @resp   NVARCHAR(MAX) OUTPUT
AS
BEGIN
    SET NOCOUNT ON;
    
    DECLARE @j NVARCHAR(MAX) = ISNULL(@rqst, N'{}');

    ------------------------------------------------------------------------
    -- ACTION: health
    -- System health overview
    ------------------------------------------------------------------------
    IF @action = 'health'
    BEGIN
        DECLARE @clientCount INT, @userCount INT, @sessionCount INT, @logCount24h INT;
        
        SELECT @clientCount = COUNT(*) FROM dbo.tbClient WHERE cltStatus = 'Active';
        SELECT @userCount = COUNT(*) FROM dbo.tbUser WHERE usrStatus = 'Active';
        SELECT @sessionCount = COUNT(*) FROM dbo.tbSession WHERE sesIsRevoked = 0 AND sesExpiresUtc > SYSUTCDATETIME();
        
        -- Check if tbAdpApiLog exists (may not be in all installations)
        IF OBJECT_ID('dbo.tbAdpApiLog', 'U') IS NOT NULL
            EXEC sp_executesql N'SELECT @cnt = COUNT(*) FROM dbo.tbAdpApiLog WHERE createdUtc > DATEADD(HOUR, -24, SYSUTCDATETIME())', 
                N'@cnt INT OUTPUT', @cnt = @logCount24h OUTPUT;
        ELSE
            SET @logCount24h = 0;

        SET @resp = (
            SELECT 
                CAST(1 AS BIT) AS ok,
                @clientCount AS activeClients,
                @userCount AS activeUsers,
                @sessionCount AS activeSessions,
                @logCount24h AS apiCalls24h,
                SYSUTCDATETIME() AS serverTimeUtc
            FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
        );
        RETURN;
    END

    ------------------------------------------------------------------------
    -- ACTION: stats
    -- Detailed statistics
    ------------------------------------------------------------------------
    IF @action = 'stats'
    BEGIN
        DECLARE @hours INT = ISNULL(TRY_CAST(JSON_VALUE(@j, '$.hours') AS INT), 24);

        -- Clients by status
        DECLARE @clientsByStatus NVARCHAR(MAX);
        SELECT @clientsByStatus = (
            SELECT cltStatus AS status, COUNT(*) AS [count]
            FROM dbo.tbClient
            GROUP BY cltStatus
            FOR JSON PATH
        );

        -- Users by status
        DECLARE @usersByStatus NVARCHAR(MAX);
        SELECT @usersByStatus = (
            SELECT usrStatus AS status, COUNT(*) AS [count]
            FROM dbo.tbUser
            GROUP BY usrStatus
            FOR JSON PATH
        );

        -- Sessions stats
        DECLARE @activeSessions INT, @expiredSessions INT, @revokedSessions INT;
        SELECT @activeSessions = COUNT(*) FROM dbo.tbSession 
            WHERE sesIsRevoked = 0 AND sesExpiresUtc > SYSUTCDATETIME();
        SELECT @expiredSessions = COUNT(*) FROM dbo.tbSession 
            WHERE sesIsRevoked = 0 AND sesExpiresUtc <= SYSUTCDATETIME();
        SELECT @revokedSessions = COUNT(*) FROM dbo.tbSession 
            WHERE sesIsRevoked = 1;

        -- Recent registrations (last 7 days)
        DECLARE @recentClients INT, @recentUsers INT;
        SELECT @recentClients = COUNT(*) FROM dbo.tbClient 
            WHERE cltCreatedUtc > DATEADD(DAY, -7, SYSUTCDATETIME());
        SELECT @recentUsers = COUNT(*) FROM dbo.tbUser 
            WHERE usrCreatedUtc > DATEADD(DAY, -7, SYSUTCDATETIME());

        SET @resp = (
            SELECT 
                CAST(1 AS BIT) AS ok,
                JSON_QUERY(ISNULL(@clientsByStatus, '[]')) AS clientsByStatus,
                JSON_QUERY(ISNULL(@usersByStatus, '[]')) AS usersByStatus,
                @activeSessions AS activeSessions,
                @expiredSessions AS expiredSessions,
                @revokedSessions AS revokedSessions,
                @recentClients AS newClientsLast7Days,
                @recentUsers AS newUsersLast7Days,
                SYSUTCDATETIME() AS serverTimeUtc
            FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
        );
        RETURN;
    END

    SET @resp = N'{"ok":false,"error":"Unknown action"}';
END
GO
