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

    ------------------------------------------------------------------------
    -- ACTION: create
    ------------------------------------------------------------------------
    IF @action = 'create'
    BEGIN
        DECLARE @cName NVARCHAR(200) = NULLIF(JSON_VALUE(@j, '$.clientName'), '');

        IF @cName IS NULL
        BEGIN
            SET @resp = N'{"ok":false,"error":"clientName is required"}';
            RETURN;
        END

        IF EXISTS (SELECT 1 FROM dbo.tbClient WHERE cltName = @cName)
        BEGIN
            SET @resp = N'{"ok":false,"error":"Client name already exists"}';
            RETURN;
        END

        DECLARE @cId UNIQUEIDENTIFIER = NEWID();
        INSERT INTO dbo.tbClient (cltId, cltName, cltStatus)
        VALUES (@cId, @cName, 'Active');

        SET @resp = (
            SELECT 
                CAST(1 AS BIT) AS ok,
                @cId AS clientId,
                @cName AS clientName,
                'Active' AS status
            FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
        );
        RETURN;
    END

    ------------------------------------------------------------------------
    -- ACTION: get
    ------------------------------------------------------------------------
    IF @action = 'get'
    BEGIN
        DECLARE @gId UNIQUEIDENTIFIER = TRY_CONVERT(UNIQUEIDENTIFIER, JSON_VALUE(@j, '$.clientId'));

        IF @gId IS NULL
        BEGIN
            SET @resp = N'{"ok":false,"error":"clientId is required"}';
            RETURN;
        END

        IF NOT EXISTS (SELECT 1 FROM dbo.tbClient WHERE cltId = @gId)
        BEGIN
            SET @resp = N'{"ok":false,"error":"Client not found"}';
            RETURN;
        END

        SET @resp = (
            SELECT 
                CAST(1 AS BIT) AS ok,
                c.cltId AS clientId,
                c.cltName AS clientName,
                c.cltStatus AS status,
                c.cltCreatedUtc AS createdAt,
                (SELECT COUNT(*) FROM dbo.tbUserClientRole WHERE ucrCltId = c.cltId) AS userCount,
                (SELECT COUNT(*) FROM dbo.tbAdAccount WHERE accCltId = c.cltId) AS accountCount
            FROM dbo.tbClient c WHERE c.cltId = @gId
            FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
        );
        RETURN;
    END

    ------------------------------------------------------------------------
    -- ACTION: list
    ------------------------------------------------------------------------
    IF @action = 'list'
    BEGIN
        DECLARE @lStatus VARCHAR(20) = NULLIF(JSON_VALUE(@j, '$.status'), '');
        DECLARE @lPage INT = ISNULL(TRY_CAST(JSON_VALUE(@j, '$.page') AS INT), 1);
        DECLARE @lPageSize INT = ISNULL(TRY_CAST(JSON_VALUE(@j, '$.pageSize') AS INT), 50);

        DECLARE @clients NVARCHAR(MAX);
        SELECT @clients = (
            SELECT 
                c.cltId AS clientId,
                c.cltName AS clientName,
                c.cltStatus AS status,
                c.cltCreatedUtc AS createdAt,
                (SELECT COUNT(*) FROM dbo.tbUserClientRole WHERE ucrCltId = c.cltId) AS userCount
            FROM dbo.tbClient c
            WHERE @lStatus IS NULL OR c.cltStatus = @lStatus
            ORDER BY c.cltName
            OFFSET (@lPage - 1) * @lPageSize ROWS
            FETCH NEXT @lPageSize ROWS ONLY
            FOR JSON PATH
        );

        DECLARE @lTotal INT;
        SELECT @lTotal = COUNT(*) FROM dbo.tbClient WHERE @lStatus IS NULL OR cltStatus = @lStatus;

        SET @resp = (
            SELECT 
                CAST(1 AS BIT) AS ok,
                JSON_QUERY(ISNULL(@clients, '[]')) AS clients,
                @lTotal AS totalCount,
                @lPage AS page,
                @lPageSize AS pageSize
            FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
        );
        RETURN;
    END

    ------------------------------------------------------------------------
    -- ACTION: update
    ------------------------------------------------------------------------
    IF @action = 'update'
    BEGIN
        DECLARE @uId UNIQUEIDENTIFIER = TRY_CONVERT(UNIQUEIDENTIFIER, JSON_VALUE(@j, '$.clientId'));
        DECLARE @uName NVARCHAR(200) = NULLIF(JSON_VALUE(@j, '$.clientName'), '');
        DECLARE @uStatus VARCHAR(20) = NULLIF(JSON_VALUE(@j, '$.status'), '');

        IF @uId IS NULL
        BEGIN
            SET @resp = N'{"ok":false,"error":"clientId is required"}';
            RETURN;
        END

        IF NOT EXISTS (SELECT 1 FROM dbo.tbClient WHERE cltId = @uId)
        BEGIN
            SET @resp = N'{"ok":false,"error":"Client not found"}';
            RETURN;
        END

        UPDATE dbo.tbClient
        SET cltName = ISNULL(@uName, cltName),
            cltStatus = ISNULL(@uStatus, cltStatus)
        WHERE cltId = @uId;

        SET @resp = (
            SELECT 
                CAST(1 AS BIT) AS ok,
                cltId AS clientId,
                cltName AS clientName,
                cltStatus AS status
            FROM dbo.tbClient WHERE cltId = @uId
            FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
        );
        RETURN;
    END

    ------------------------------------------------------------------------
    -- ACTION: delete (soft delete)
    ------------------------------------------------------------------------
    IF @action = 'delete'
    BEGIN
        DECLARE @dId UNIQUEIDENTIFIER = TRY_CONVERT(UNIQUEIDENTIFIER, JSON_VALUE(@j, '$.clientId'));

        IF @dId IS NULL
        BEGIN
            SET @resp = N'{"ok":false,"error":"clientId is required"}';
            RETURN;
        END

        UPDATE dbo.tbClient SET cltStatus = 'Inactive' WHERE cltId = @dId;

        SET @resp = (SELECT CAST(1 AS BIT) AS ok, @@ROWCOUNT AS rowsAffected FOR JSON PATH, WITHOUT_ARRAY_WRAPPER);
        RETURN;
    END

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