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

    ------------------------------------------------------------------------
    -- ACTION: status
    -- Check if user is registered and has client access
    ------------------------------------------------------------------------
    IF @action = 'status'
    BEGIN
        DECLARE @sSubject NVARCHAR(200) = NULLIF(JSON_VALUE(@j, '$.subject'), '');
        DECLARE @sEmail NVARCHAR(256) = NULLIF(JSON_VALUE(@j, '$.email'), '');

        DECLARE @sUserId UNIQUEIDENTIFIER;
        DECLARE @sUserEmail NVARCHAR(256);
        
        SELECT @sUserId = usrId, @sUserEmail = usrEmail
        FROM dbo.tbUser
        WHERE usrEntraSub = @sSubject;

        -- User doesn't exist
        IF @sUserId IS NULL
        BEGIN
            SET @resp = (
                SELECT 
                    CAST(1 AS BIT) AS ok,
                    CAST(0 AS BIT) AS isRegistered,
                    @sEmail AS email
                FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
            );
            RETURN;
        END

        -- Check for client access
        DECLARE @clients NVARCHAR(MAX);
        SELECT @clients = (
            SELECT 
                c.cltId AS clientId,
                c.cltName AS clientName,
                r.ucrRole AS [role]
            FROM dbo.tbUserClientRole r
            JOIN dbo.tbClient c ON c.cltId = r.ucrCltId AND c.cltStatus = 'Active'
            WHERE r.ucrUsrId = @sUserId
            FOR JSON PATH
        );

        IF @clients IS NULL OR @clients = '[]'
        BEGIN
            SET @resp = (
                SELECT 
                    CAST(1 AS BIT) AS ok,
                    CAST(0 AS BIT) AS isRegistered,
                    @sUserId AS userId,
                    @sUserEmail AS email
                FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
            );
            RETURN;
        END

        SET @resp = (
            SELECT 
                CAST(1 AS BIT) AS ok,
                CAST(1 AS BIT) AS isRegistered,
                @sUserId AS userId,
                @sUserEmail AS email,
                JSON_QUERY(@clients) AS clients
            FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
        );
        RETURN;
    END

    ------------------------------------------------------------------------
    -- ACTION: register
    -- Creates client + links user as Admin
    ------------------------------------------------------------------------
    IF @action = 'register'
    BEGIN
        DECLARE @provider VARCHAR(30) = NULLIF(JSON_VALUE(@j, '$.provider'), '');
        DECLARE @subject NVARCHAR(200) = NULLIF(JSON_VALUE(@j, '$.subject'), '');
        DECLARE @email NVARCHAR(256) = NULLIF(JSON_VALUE(@j, '$.email'), '');
        DECLARE @displayName NVARCHAR(256) = NULLIF(JSON_VALUE(@j, '$.displayName'), '');
        DECLARE @clientName NVARCHAR(200) = NULLIF(JSON_VALUE(@j, '$.clientName'), '');

        -- Validation
        IF @provider IS NULL OR @subject IS NULL
        BEGIN
            SET @resp = N'{"ok":false,"error":"provider and subject are required"}';
            RETURN;
        END

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

        -- Find or create user
        DECLARE @userId UNIQUEIDENTIFIER;
        
        SELECT @userId = usrId
        FROM dbo.tbUser
        WHERE usrEntraSub = @subject;

        IF @userId IS NULL
        BEGIN
            SET @userId = NEWID();
            INSERT dbo.tbUser (usrId, usrEntraSub, usrProvider, usrSubject, usrEmail, usrDisplayName, usrStatus)
            VALUES (@userId, @subject, @provider, @subject, @email, @displayName, 'Active');
        END

        -- Check if user already has client access
        IF EXISTS (SELECT 1 FROM dbo.tbUserClientRole WHERE ucrUsrId = @userId)
        BEGIN
            SET @resp = N'{"ok":false,"error":"User is already registered"}';
            RETURN;
        END

        -- Create client
        DECLARE @clientId UNIQUEIDENTIFIER = NEWID();
        INSERT dbo.tbClient (cltId, cltName, cltStatus)
        VALUES (@clientId, @clientName, 'Active');

        -- Link user as Admin
        INSERT dbo.tbUserClientRole (ucrUsrId, ucrCltId, ucrRole)
        VALUES (@userId, @clientId, 'Admin');

        -- Return success
        SET @resp = (
            SELECT 
                CAST(1 AS BIT) AS ok,
                @userId AS userId,
                @clientId AS clientId,
                @clientName AS clientName,
                'Admin' AS [role]
            FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
        );
        RETURN;
    END

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