

USE demo;
 
DROP PROCEDURE IF EXISTS p_dog_save_new_founding_partner;


DELIMITER //
CREATE PROCEDURE p_dog_save_new_founding_partner (
      IN a_comment VARCHAR(500)
	, IN a_guid BINARY(36)
    , IN a_id_user_auth0 VARCHAR(256)
    , IN a_email_user VARCHAR(256)
    , IN a_debug BIT
)
BEGIN
	DECLARE v_code_type_error_bad_data VARCHAR(100);
    DECLARE v_id_access_level_edit INT;
    DECLARE v_id_change_set INT;
    DECLARE v_id_permission_product INT;
    DECLARE v_id_permission_user_edit INT;
    DECLARE v_id_role_manager INT;
    DECLARE v_is_super_user BIT;
    DECLARE v_id_type_error_bad_data INT;
    DECLARE v_can_edit_user BIT;
    DECLARE v_priority_access_level_admin INT;
    DECLARE v_priority_access_level_none INT;
    DECLARE v_priority_access_level_user INT;
    DECLARE v_time_start TIMESTAMP(6);
    
    DECLARE exit handler for SQLEXCEPTION
    BEGIN
        GET DIAGNOSTICS CONDITION 1
            @sqlstate = RETURNED_SQLSTATE
            , @errno = MYSQL_ERRNO
            , @text = MESSAGE_TEXT
		;
        
        ROLLBACK;
        
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Msg_Error (
			display_order INT NOT NULL PRIMARY KEY AUTO_INCREMENT
			, id_type INT
			, code VARCHAR(250) NOT NULL
			, msg TEXT NOT NULL
		);
        INSERT INTO tmp_Msg_Error (
			id_type
            , code
            , msg
		)
        SELECT 
			MET.id_type
            , @errno
            , @text
		FROM demo.CORE_Msg_Error_Type MET
        WHERE MET.code = 'MYSQL_ERROR'
		;
        SELECT *
        FROM tmp_Msg_Error;
		DROP TABLE IF EXISTS tmp_Msg_Error;
    END;
    
    SET v_time_start := CURRENT_TIMESTAMP(6);
    SET v_code_type_error_bad_data := 'BAD_DATA';
    SET v_id_type_error_bad_data := (SELECT ERROR_TYPE.id_type FROM demo.CORE_Msg_Error_Type ERROR_TYPE WHERE ERROR_TYPE.code = v_code_type_error_bad_data LIMIT 1);
    SET v_id_access_level_edit := (SELECT ACCESS_LEVEL.id_access_level FROM demo.DOG_Access_Level ACCESS_LEVEL WHERE ACCESS_LEVEL.code = 'EDIT' LIMIT 1);
    SET v_id_permission_user_edit := (SELECT GROUP_CONCAT(PERMISSION.id_permission SEPARATOR ',') FROM demo.DOG_Permission PERMISSION WHERE PERMISSION.code = 'USER_CREATE' LIMIT 1);
    SET v_priority_access_level_admin := (SELECT ACCESS_LEVEL.priority FROM demo.DOG_Access_Level ACCESS_LEVEL WHERE ACCESS_LEVEL.code = 'ADMIN' LIMIT 1);
    SET v_priority_access_level_none := (SELECT ACCESS_LEVEL.priority FROM demo.DOG_Access_Level ACCESS_LEVEL WHERE ACCESS_LEVEL.code = 'NONE' LIMIT 1);
    SET v_id_role_manager := (SELECT ROLES.id_role FROM demo.DOG_Role ROLES WHERE ROLES.code = 'COMPANY_MANAGER' LIMIT 1);

    CALL demo.p_core_validate_guid ( a_guid );
    
    DROP TABLE IF EXISTS tmp_Msg_Error;
    DROP TABLE IF EXISTS tmp_User_Save_User;
    
    CREATE TABLE tmp_User_Save_User (
		id_user INT NOT NULL
        , id_role INT
        , id_user_auth0 VARCHAR(250)
        , firstname VARCHAR(250)
        , surname VARCHAR(250)
        , email VARCHAR(254)
        , is_email_verified BIT DEFAULT 0
        , is_super_user BIT DEFAULT 0
        , active BIT DEFAULT 1
        , name_error VARCHAR(1000)
    );
    
    CREATE TABLE tmp_Msg_Error (
		display_order INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
		id_type INT NOT NULL,
        code VARCHAR(250) NOT NULL,
		msg TEXT NOT NULL
    );
    
    IF NOT EXISTS (SELECT * FROM demo.PH_Apply_Founding_Partner_Form AFPF WHERE AFPF.email = a_email_user) THEN
        INSERT INTO tmp_Msg_Error (
			id_type
            , code
            , msg
		)
        SELECT 
			MET.id_type
            , MET.code
            , 'Founding Partner not found.'
		FROM demo.CORE_Msg_Error_Type MET
        WHERE MET.id_type = v_id_type_error_bad_data
		;
    END IF;

    -- Get data from Temp table
    INSERT INTO tmp_User_Save_User (
		id_user
        , id_user_auth0
        , id_role
        , email
        , firstname
        , surname
        , name_error
	)
    VALUES ( 
          -1 -- AS id_user
        , a_id_user_auth0
        , v_id_role_manager
        , a_email_user
        , (SELECT LEFT(AFPF.name_contact, LOCATE(' ', AFPF.name_contact) - 1) FROM demo.PH_Apply_Founding_Partner_Form AFPF WHERE AFPF.email = a_email_user) -- AS firstname
        , (SELECT SUBSTRING(AFPF.name_contact, LOCATE(' ', AFPF.name_contact) + 1) FROM demo.PH_Apply_Founding_Partner_Form AFPF WHERE AFPF.email = a_email_user) -- AS surname
        , COALESCE(a_email_user, a_id_user_auth0) -- AS name_error
    );

    
    IF NOT EXISTS (SELECT * FROM tmp_Msg_Error LIMIT 1) THEN
		START TRANSACTION;
        
            INSERT INTO demo.DOG_User (
                  id_user_auth0
                , firstname
                , surname
                , email
                , is_email_verified
                , is_super_user
                , active
            )
            SELECT
                  t_USER.id_user_auth0
                , t_USER.firstname
                , t_USER.surname
                , t_USER.email
                , t_USER.is_email_verified
                , t_USER.is_super_user
                , t_USER.active
            FROM tmp_User_Save_User t_USER
            ;

            UPDATE tmp_User_Save_User t_USER
            INNER JOIN demo.DOG_User USER ON t_USER.id_user_auth0 = USER.id_user_auth0
            SET t_USER.id_user = USER.id_user
            ;
            
            INSERT INTO demo.DOG_User_Role_Link (
                  id_role
                , id_user
                , active
                , id_user_created_by
                , created_on
            )
            SELECT
                  t_USER.id_role
                , t_USER.id_user
                , 1 -- active
                , t_USER.id_user                                     AS created_by
                , v_time_start                                  AS created_on
            FROM tmp_User_Save_User t_USER
            ;
            
		COMMIT;
    END IF;
	
    # Errors
    SELECT *
    FROM tmp_Msg_Error t_ME
	INNER JOIN demo.CORE_Msg_Error_Type MET ON t_ME.id_type = MET.id_type
	;
    
	IF a_debug = 1 THEN
		SELECT * from tmp_User_Save_User;
	END IF;

    DROP TABLE IF EXISTS tmp_Msg_Error;
    DROP TABLE IF EXISTS tmp_User_Save_User;
    
	IF a_debug = 1 THEN
		CALL demo.p_debug_timing_reporting ( v_time_start );
	END IF;
END //
DELIMITER ;



SELECT *
FROM demo.PH_Apply_Founding_Partner_Form;
SELECT *
FROM demo.DOG_User;

CALL demo.p_dog_save_new_founding_partner (
    'Test' -- a_comment
    , 'lipsandchipsanddipslipsandchipsanddi' -- a_guid
    , 'nipples' -- id_user-auth0
    , 'edwardmanic.ms@gmail.com' -- email -- 'teddy@demoltd.co.uk'
    , 0 -- debug
);

SELECT *
FROM demo.DOG_User;
