
CREATE OR REPLACE PROCEDURE tcg.public.USP_TCG_User_Login (
      a_user_auth0_id TEXT
    , a_email TEXT
    , a_guid UUID
    , a_is_email_verified BOOLEAN
	, OUT o_success BOOLEAN
    , OUT o_user_id INT
)
LANGUAGE plpgsql
AS $$
DECLARE
	v_bad_data_error_type_id INT;
	v_bot_user_id INT;
	v_change_set_id INT;
    v_email TEXT;
	-- v_error_message TEXT;
	v_guid UUID;
    v_is_email_verified BOOLEAN;
	v_time_start TIMESTAMP;
    v_user_auth0_id TEXT;
	v_warning_error_type_id INT;
BEGIN
	v_user_auth0_id := TRIM(COALESCE(a_user_auth0_id, ''));
    v_email := TRIM(COALESCE(a_email, ''));
    v_is_email_verified := COALESCE(a_is_email_verified, FALSE);

	v_bad_data_error_type_id := (SELECT ERROR_TYPE.error_type_id FROM tcg.public.Error_Type ERROR_TYPE WHERE ERROR_TYPE.code = 'BAD_DATA' LIMIT 1);
	v_warning_error_type_id := (SELECT ERROR_TYPE.error_type_id FROM tcg.public.Error_Type ERROR_TYPE WHERE ERROR_TYPE.code = 'WARNING' LIMIT 1);
	v_bot_user_id := 6;
	v_time_start := CURRENT_TIMESTAMP;

    o_success := FALSE;
	
	-- DROP TABLE IF EXISTS Temp_User_Save_User;
	DROP TABLE IF EXISTS Temp_User_Save_Error;
    
    /*
    CREATE TEMP TABLE Temp_User_Save_User (
          user_id INT NOT NULL
        , user_auth0_id TEXT
        , firstname TEXT
        , surname TEXT
        , email TEXT
        , is_email_verified BOOLEAN
        , is_super_user BOOLEAN
        , active BOOLEAN
        , created_on TIMESTAMP
        , created_by_user_id INT
        , updated_last_on TIMESTAMP
        , updated_last_by_user_id INT
        , change_set_id INT
    );
    */

	CREATE TEMP TABLE Temp_User_Save_Error (
		  temp_id INT GENERATED ALWAYS AS IDENTITY
		, error_type_id INT
		, message TEXT
	);

    IF v_user_auth0_id = '' THEN
        INSERT INTO Temp_User_Save_Error (
			  error_type_id
			, message
		)
		VALUES (
			  v_bad_data_error_type_id
			, 'User Auth0 ID required.'
		);
    END IF;
	
    /*
	INSERT INTO Temp_User_Save_User (
          user_id
        , user_auth0_id
        , firstname
        , surname
        , email
        , is_email_verified
        , is_super_user
        , active
        , created_on
        , created_by_user_id
        , updated_last_on
        , updated_last_by_user_id
        , change_set_id
    )
	SELECT
          TCG_USER.user_id
        , v_user_auth0_id
        , TCG_USER.firstname
        , TCG_USER.surname
        , TCG_USER.email
        , TCG_USER.is_email_verified
        , TCG_USER.is_super_user
        , COALESCE(TCG_USER.active, TRUE)
        , COALESCE(TCG_USER.created_on, v_time_start) -- created_on
        , COALESCE(TCG_USER.created_by_user_id, v_bot_user_id) -- created_by_user_id
        , COALESCE(TCG_USER.updated_last_on, v_time_start) -- updated_last_on
        , COALESCE(TCG_USER.updated_last_by_user_id, v_bot_user_id) -- updated_last_by_user_id
        , TCG_USER.change_set_id
	FROM tcg.public.TCG_User TCG_USER
	WHERE
            TCG_USER.user_auth0_id = v_user_auth0_id
        OR  TCG_USER.email = v_email
	;
    */

	-- Outputs
	-- Change Set
	INSERT INTO tcg.public.TCG_Change_Set (
		  comment
		, updated_last_by_user_id
	)
	VALUES (
		  'Save User'
		, v_bot_user_id
	)
	RETURNING change_set_id INTO v_change_set_id
	;
	
	IF NOT EXISTS (SELECT * FROM Temp_User_Save_Error T_ERROR WHERE T_ERROR.error_type_id <> v_warning_error_type_id LIMIT 1) THEN
		
        IF NOT EXISTS (
            SELECT *
            FROM tcg.public.TCG_User TCG_USER
            WHERE
                    TCG_USER.user_auth0_id = v_user_auth0_id
                OR  TCG_USER.email = v_email
            LIMIT 1
        ) THEN
            -- RAISE EXCEPTION 'Valid User Auth0 ID required.';

            -- New User
            INSERT INTO tcg.public.TCG_User (
                  user_auth0_id
                , firstname
                , surname
                , email
                , is_email_verified
                , is_super_user
                , active
                , created_on
                , created_by_user_id
                , updated_last_on
                , updated_last_by_user_id
                , change_set_id
            )
            VALUES (
                  v_user_auth0_id -- user_auth0_id
                , '' -- firstname
                , '' -- surname
                , v_email -- email
                , v_is_email_verified -- is_email_verified
                , FALSE -- is_super_user
                , TRUE -- active
                , v_time_start -- created_on
                , v_bot_user_id -- created_by_user_id
                , v_time_start -- updated_last_on
                , v_bot_user_id -- updated_last_by_user_id
                , v_change_set_id -- change_set_id
            );
        ELSEIF NOT EXISTS (
            SELECT *
            FROM tcg.public.TCG_User TCG_USER
            WHERE TCG_USER.user_auth0_id = v_user_auth0_id
        ) THEN
            UPDATE tcg.public.TCG_User TCG_USER
            SET
                  user_auth0_id = v_user_auth0_id
                , change_set_id = v_change_set_id
            WHERE
                    TCG_USER.email = v_email
                AND TCG_USER.active
            ;
        END IF;
	ELSE
		-- Error
		INSERT INTO tcg.public.Error (
			  guid
			, error_type_id
			, message
			, display_order
			, created_on
			, created_by_user_id
			, updated_last_on
			, updated_last_by_user_id
			, change_set_id
		)
		SELECT
			  a_guid
			, T_ERROR.error_type_id
			, T_ERROR.message
			, T_ERROR.temp_id
			, v_time_start
			, a_user_id
			, v_time_start
			, a_user_id
			, v_change_set_id
		FROM Temp_User_Save_Error T_ERROR
		LEFT JOIN tcg.public.Error_Type ERROR_TYPE ON T_ERROR.error_type_id = ERROR_TYPE.error_type_id
		ORDER BY T_ERROR.temp_id
		;
	END IF;

    COMMIT;
	
    o_user_id := (
        SELECT TCG_USER.user_id
        FROM tcg.public.TCG_User TCG_USER
        WHERE TCG_USER.user_auth0_id = v_user_auth0_id
        ORDER BY TCG_USER.user_id DESC
        LIMIT 1
    );

	o_success := (
            NOT EXISTS (
            SELECT *
            FROM Temp_User_Save_Error T_ERROR
            WHERE T_ERROR.error_type_id <> v_warning_error_type_id
            LIMIT 1
        )
        AND o_user_id IS NOT NULL
    );
	
	DROP TABLE IF EXISTS Temp_User_Save_User;
	DROP TABLE IF EXISTS Temp_User_Save_Error;
END;
$$;


-- Call it with:
DO $$
DECLARE
    v_user_auth0_id TEXT := 'auth0|6582b95c895d09a70ba10fef';
    v_email TEXT := 'edward.middletonsmith@gmail.com';
	v_guid UUID = '5555092c-d8b6-45b6-9ae4-f29a554d8a16';
    v_is_email_verified BOOLEAN := False;
	
    v_success BOOLEAN := False;
    v_user_id INT = NULL;
BEGIN
	-- v_guid := gen_random_uuid();

    CALL tcg.public.USP_TCG_User_Login (
		  v_user_auth0_id -- a_user_auth0_id
		, v_email -- a_email
		, v_guid -- a_guid
		, v_is_email_verified -- a_is_email_verified
		, v_success -- o_success
        , v_user_id -- o_user_id
	);
    RAISE NOTICE 'Success: %\nUser ID: %', CASE WHEN v_success THEN 'TRUE' ELSE 'FALSE' END, CAST(v_user_id AS VARCHAR);
END;
$$;

SELECT *
-- DELETE
FROM tcg.public.Error ERROR
LEFT JOIN tcg.public.Error_Type ERROR_TYPE ON ERROR.error_type_id = ERROR_TYPE.error_type_id
;
SELECT *
FROM tcg.public.Error_Type ERROR_TYPE
;
SELECT *
FROM tcg.public.TCG_Change_Set CHANGE_SET
ORDER BY CHANGE_SET.change_set_id  DESC
;
/*
SELECT *
FROM tcg.public.TCG_MTG_Game
;
*/
SELECT *
-- DELETE
FROM tcg.public.TCG_User TCG_USER
ORDER BY TCG_USER.user_id DESC
;


/*


SELECT *
FROM tcg.public.TCG_User TCG_USER
;

INSERT INTO tcg.public.tcg_change_set (
	COMMENT, updated_last_by_user_id
)
VALUES ( 'Clear Auth0 id from Teddy.', 3);

SELECT *
FROM tcg.public.tcg_change_set cs
ORDER BY cs.change_set_id  DESC
;
UPDATE tcg.public.TCG_User TCG_USER
SET
	  user_auth0_id = NULL
	, change_set_id = 224
WHERE TCG_USER.user_id = 3
;
DELETE FROM tcg.public.TCG_User TCG_USER
WHERE TCG_USER.user_id = 13
;

*/

