
CREATE OR REPLACE PROCEDURE tcg.public.USP_TCG_MTG_Game_Round_Damage_Save (
      a_comment TEXT
    , a_guid UUID
    , a_user_id INT
	, OUT o_success BOOLEAN
)
LANGUAGE plpgsql
AS $$
DECLARE
	v_bad_data_error_type_id INT;
	v_change_set_id INT;
	v_commander_damage_limit INT := 21;
	v_comment TEXT;
	-- v_error_message TEXT;
	v_guid UUID;
    v_no_permission_error_type_id INT;
	v_time_start TIMESTAMP;
	v_user_id INT;
	v_warning_error_type_id INT;
BEGIN
	v_comment := TRIM(COALESCE(a_comment, ''));
	v_guid := a_guid;
	v_user_id := a_user_id;

	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_no_permission_error_type_id := (SELECT ERROR_TYPE.error_type_id FROM tcg.public.Error_Type ERROR_TYPE WHERE ERROR_TYPE.code = 'NO_PERMISSION' 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_time_start := CURRENT_TIMESTAMP;
	
	DROP TABLE IF EXISTS Temp_MTG_Round_Damage_Save_Game;
	DROP TABLE IF EXISTS Temp_MTG_Round_Damage_Save_Player;
	DROP TABLE IF EXISTS Temp_MTG_Round_Damage_Save_Round;
	DROP TABLE IF EXISTS Temp_MTG_Round_Damage_Save_Round_Player_Damage;
	DROP TABLE IF EXISTS Temp_MTG_Round_Damage_Save_Player_Round_Link;
	DROP TABLE IF EXISTS Temp_MTG_Round_Damage_Save_Error;
    
    CREATE TEMP TABLE Temp_MTG_Round_Damage_Save_Game (
          game_id INT NOT NULL
        , notes TEXT
        , is_commander BOOLEAN
        , is_draft BOOLEAN
        , is_sealed BOOLEAN
        , location_name TEXT
        , start_on TIMESTAMP
        , end_on TIMESTAMP
        , starting_life INT
        , active BOOLEAN
        , created_on TIMESTAMP
        , created_by_user_id INT
        , updated_last_on TIMESTAMP
        , updated_last_by_user_id INT
        , change_set_id INT

        , max_round_display_order INT
        , count_players INT
        , duration INTERVAL
    );

    CREATE TEMP TABLE Temp_MTG_Round_Damage_Save_Player (
          player_id INT NOT NULL
        , game_id INT
        , user_id INT
        , deck_id INT
        , name TEXT
        , notes TEXT
        , display_order INT
        , active BOOLEAN
        , created_on TIMESTAMP
        , created_by_user_id INT
        , updated_last_on TIMESTAMP
        , updated_last_by_user_id INT
		, change_set_id INT

        , round_display_order_eliminated INT
        , final_player_damage_round_id INT
        , placement INT
        , max_total_commander_damage_received INT
        , total_commander_damage_dealt INT
        , total_damage_received INT
        , total_life_gained INT
        , total_commander_deaths INT
    );

    CREATE TEMP TABLE Temp_MTG_Round_Damage_Save_Round (
          temp_id INT NOT NULL
        , round_id INT
        , game_id INT
        , notes TEXT
        , display_order INT
        , active BOOLEAN
        , created_on TIMESTAMP
        , created_by_user_id INT
        , updated_last_on TIMESTAMP
        , updated_last_by_user_id INT
		, change_set_id INT

        , is_new BOOLEAN
        , error_name TEXT
        , is_duplicate BOOLEAN DEFAULT FALSE
        , count_survivors INT
    );

    CREATE TEMP TABLE Temp_MTG_Round_Damage_Save_Round_Player_Damage (
          temp_id INT NOT NULL
        , damage_id INT
        , temp_round_id INT
        , round_id INT
        , player_id INT
        , received_from_commander_player_id INT
		, life_gain INT
		, life_loss INT
        , commander_deaths INT
		, is_eliminated 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

        , is_new BOOLEAN
        , error_name TEXT
        , is_duplicate BOOLEAN DEFAULT FALSE
    );

    CREATE TEMP TABLE Temp_MTG_Round_Damage_Save_Player_Round_Link (
          game_id INT
        , player_id INT
        , round_id INT
        
        , is_eliminated BOOLEAN
        , max_total_commander_damage_received INT
        , total_commander_damage_dealt INT
        , total_damage_received INT
        , total_commander_deaths INT
        , total_life_gained INT
    );

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

    IF NOT EXISTS (SELECT * FROM tcg.public.TCG_User TCG_USER WHERE TCG_USER.user_id = v_user_id LIMIT 1) THEN
        INSERT INTO Temp_MTG_Round_Damage_Save_Error (
            error_type_id
            , message
        )
        VALUES (
            v_no_permission_error_type_id -- error_type_id
            , CONCAT(
                'User does not exist: '
                , CAST(v_user_id AS VARCHAR)
                , '.'
            ) -- message
        );
    END IF;
	
	WITH Temp_Round AS (
		SELECT
			  ROUND_T.temp_id
	        , CASE WHEN COALESCE(ROUND_T.round_id, 0) < 1 
				THEN COALESCE(TCG_ROUND.round_id, ROUND_T.round_id, 0)
				ELSE ROUND_T.round_id
			END AS round_id
	        , ROUND_T.game_id
	        , ROUND_T.notes
	        , ROUND_T.display_order
	        , COALESCE(ROUND_T.active, TRUE) AS active
	        , COALESCE(ROUND_T.created_on, v_time_start) AS created_on
	        , COALESCE(ROUND_T.created_by_user_id, v_user_id) AS created_by_user_id
	        , COALESCE(ROUND_T.updated_last_on, v_time_start) AS updated_last_on
	        , COALESCE(ROUND_T.updated_last_by_user_id, v_user_id) AS updated_last_by_user_id	FROM tcg.public.TCG_MTG_Game_Round_Temp ROUND_T
		LEFT JOIN tcg.public.TCG_MTG_Game_Round TCG_ROUND
			ON  ROUND_T.round_id = TCG_ROUND.round_id
			OR  (
					COALESCE(ROUND_T.round_id, 0) < 1
				AND ROUND_T.game_id = TCG_ROUND.game_id
				AND ROUND_T.display_order = TCG_ROUND.display_order
			)
		WHERE ROUND_T.guid = v_guid
	)
	INSERT INTO Temp_MTG_Round_Damage_Save_Round (
		  temp_id
        , round_id
        , game_id
        , notes
        , display_order
        , active
        , created_on
        , created_by_user_id
        , updated_last_on
        , updated_last_by_user_id

		, is_new
		, error_name
	)
	SELECT
		  T_ROUND.temp_id
        , T_ROUND.round_id
        , T_ROUND.game_id
        , T_ROUND.notes
        , T_ROUND.display_order
        , T_ROUND.active
        , T_ROUND.created_on
        , T_ROUND.created_by_user_id
        , T_ROUND.updated_last_on
        , T_ROUND.updated_last_by_user_id

		, CASE WHEN TCG_ROUND.round_id IS NULL THEN TRUE ELSE FALSE END AS is_new
		, CONCAT(
			  'Round { id: '
			, CAST(T_ROUND.round_id AS VARCHAR)
			, ', temp id: '
			, CAST(T_ROUND.temp_id AS VARCHAR)
			, ', display order: '
			, CAST(T_ROUND.display_order AS VARCHAR)
			, ', game id: '
			, CAST(T_ROUND.game_id AS VARCHAR)
			, ' }'
		) AS error_name
	FROM Temp_Round T_ROUND
	LEFT JOIN tcg.public.TCG_MTG_Game_Round TCG_ROUND ON T_ROUND.round_id = TCG_ROUND.round_id
	;
	
	WITH Temp_Player_Damage AS (
		SELECT
			  PLAYER_DAMAGE_T.temp_id
	        , CASE WHEN COALESCE(PLAYER_DAMAGE_T.damage_id, 0) < 1 
				THEN COALESCE(PLAYER_DAMAGE.damage_id, PLAYER_DAMAGE_T.damage_id, 0)
				ELSE PLAYER_DAMAGE_T.damage_id
			END AS damage_id
	        , T_ROUND.temp_id AS temp_round_id
	        , PLAYER_DAMAGE_T.round_id
	        , PLAYER_DAMAGE_T.player_id
	        , PLAYER_DAMAGE_T.received_from_commander_player_id
	        , ABS(COALESCE(PLAYER_DAMAGE_T.life_gain, 0)) AS life_gain
	        , ABS(COALESCE(PLAYER_DAMAGE_T.life_loss, 0)) AS life_loss
	        , COALESCE(PLAYER_DAMAGE_T.commander_deaths, 0) AS commander_deaths
			, COALESCE(PLAYER_DAMAGE_T.is_eliminated, FALSE) AS is_eliminated
	        , COALESCE(PLAYER_DAMAGE_T.active, TRUE) AS active
	        , COALESCE(PLAYER_DAMAGE_T.created_on, v_time_start) AS created_on
	        , COALESCE(PLAYER_DAMAGE_T.created_by_user_id, v_user_id) AS created_by_user_id
	        , COALESCE(PLAYER_DAMAGE_T.updated_last_on, v_time_start) AS updated_last_on
	        , COALESCE(PLAYER_DAMAGE_T.updated_last_by_user_id, v_user_id) AS updated_last_by_user_id
		FROM tcg.public.TCG_MTG_Game_Round_Player_Damage_Temp PLAYER_DAMAGE_T
		LEFT JOIN tcg.public.TCG_MTG_Game_Round_Player_Damage PLAYER_DAMAGE
			ON 	PLAYER_DAMAGE_T.damage_id = PLAYER_DAMAGE.damage_id
			OR  (
					COALESCE(PLAYER_DAMAGE_T.damage_id, 0) < 1
				AND PLAYER_DAMAGE_T.round_id = PLAYER_DAMAGE.round_id
				AND PLAYER_DAMAGE_T.player_id = PLAYER_DAMAGE.player_id
				AND (
						PLAYER_DAMAGE_T.received_from_commander_player_id = PLAYER_DAMAGE.received_from_commander_player_id
					OR  (
							PLAYER_DAMAGE_T.received_from_commander_player_id IS NULL
						AND PLAYER_DAMAGE.received_from_commander_player_id IS NULL
					)
				)
			)
	    LEFT JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND ON PLAYER_DAMAGE_T.round_id = T_ROUND.round_id
		WHERE PLAYER_DAMAGE_T.guid = v_guid
	)
	INSERT INTO Temp_MTG_Round_Damage_Save_Round_Player_Damage (
		  temp_id
        , damage_id
        , temp_round_id
        , round_id
        , player_id
        , received_from_commander_player_id
        , life_gain
        , life_loss
        , commander_deaths
		, is_eliminated
        , active
        , created_on
        , created_by_user_id
        , updated_last_on
        , updated_last_by_user_id

		, is_new
		, error_name
	)
	SELECT
		  T_PLAYER_DAMAGE.temp_id
        , T_PLAYER_DAMAGE.damage_id
        , T_PLAYER_DAMAGE.temp_round_id
        , T_PLAYER_DAMAGE.round_id
        , T_PLAYER_DAMAGE.player_id
        , T_PLAYER_DAMAGE.received_from_commander_player_id
        , T_PLAYER_DAMAGE.life_gain
        , T_PLAYER_DAMAGE.life_loss
        , T_PLAYER_DAMAGE.commander_deaths
		, T_PLAYER_DAMAGE.is_eliminated
        , T_PLAYER_DAMAGE.active
        , T_PLAYER_DAMAGE.created_on
        , T_PLAYER_DAMAGE.created_by_user_id
        , T_PLAYER_DAMAGE.updated_last_on
        , T_PLAYER_DAMAGE.updated_last_by_user_id

		, CASE WHEN PLAYER_DAMAGE.damage_id IS NULL THEN TRUE ELSE FALSE END AS is_new
		, CONCAT(
			  'Round Player Damage { id: '
			, CAST(T_PLAYER_DAMAGE.damage_id AS VARCHAR)
			, ', temp id: '
			, CAST(T_PLAYER_DAMAGE.temp_id AS VARCHAR)
			, ', round id: '
			, CAST(T_PLAYER_DAMAGE.round_id AS VARCHAR)
			, ', player id: '
			, CAST(T_PLAYER_DAMAGE.player_id AS VARCHAR)
			, ', received from commander player id: '
			, CAST(T_PLAYER_DAMAGE.received_from_commander_player_id AS VARCHAR)
			, ', life gain: '
			, CAST(T_PLAYER_DAMAGE.life_gain AS VARCHAR)
			, ', life loss: '
			, CAST(T_PLAYER_DAMAGE.life_loss AS VARCHAR)
			, ' }'
		) AS error_name
	FROM Temp_Player_Damage T_PLAYER_DAMAGE
	LEFT JOIN tcg.public.TCG_MTG_Game_Round_Player_Damage PLAYER_DAMAGE ON T_PLAYER_DAMAGE.damage_id = PLAYER_DAMAGE.damage_id
	;
	/*
	UPDATE Temp_MTG_Round_Damage_Save_Round T_ROUND
	SET round_id = COALESCE(TCG_ROUND.round_id, T_ROUND.round_id)
	FROM tcg.public.TCG_MTG_Game_Round TCG_ROUND
	WHERE
			(
				T_ROUND.round_id = TCG_ROUND.round_id
			OR  (
					T_ROUND.game_id = TCG_ROUND.game_id
				AND T_ROUND.display_order = TCG_ROUND.display_order
			)
		)
		AND COALESCE(T_ROUND.round_id, 0) < 1
	;

	UPDATE Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
	SET damage_id = COALESCE(PLAYER_DAMAGE.damage_id, T_PLAYER_DAMAGE.damage_id, 0)
	/* FROM tcg.public.TCG_MTG_Game_Round_Player_Damage PLAYER_DAMAGE
    LEFT JOIN  */
	FROM tcg.public.TCG_MTG_Game_Round_Player_Damage PLAYER_DAMAGE
	INNER JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND ON PLAYER_DAMAGE.round_id = T_ROUND.round_id
	WHERE
			( 
			 	T_PLAYER_DAMAGE.damage_id = PLAYER_DAMAGE.damage_id
			OR  (
					T_ROUND.round_id = PLAYER_DAMAGE.round_id
				AND T_PLAYER_DAMAGE.player_id = PLAYER_DAMAGE.player_id
				AND (
						T_PLAYER_DAMAGE.received_from_commander_player_id = PLAYER_DAMAGE.received_from_commander_player_id
					OR  (
							T_PLAYER_DAMAGE.received_from_commander_player_id IS NULL
						AND PLAYER_DAMAGE.received_from_commander_player_id IS NULL
					)
				)
			)
		)
		AND T_PLAYER_DAMAGE.temp_round_id = T_ROUND.temp_id
		AND COALESCE(T_PLAYER_DAMAGE.damage_id, 0) < 1
	;
	*/

    INSERT INTO Temp_MTG_Round_Damage_Save_Game (
          game_id
        , notes
        , is_commander
        , is_draft
        , is_sealed
        , location_name
        , start_on
        , end_on
        , starting_life
        , active
        , created_on
        , created_by_user_id
        , updated_last_on
        , updated_last_by_user_id
        , change_set_id
    )
	SELECT DISTINCT
		  GAME.game_id
        , GAME.notes
        , GAME.is_commander
        , GAME.is_draft
        , GAME.is_sealed
        , GAME.location_name
        , GAME.start_on
        , GAME.end_on
        , GAME.starting_life
        , GAME.active
        , GAME.created_on
        , GAME.created_by_user_id
        , GAME.updated_last_on
        , GAME.updated_last_by_user_id
        , GAME.change_set_id
	FROM tcg.public.TCG_MTG_Game GAME
	INNER JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND ON GAME.game_id = T_ROUND.game_id
	;
	
	INSERT INTO Temp_MTG_Round_Damage_Save_Player (
		  player_id
        , game_id
        , user_id
        , deck_id
        , name
        , notes
        , display_order
        , active
        , created_on
        , created_by_user_id
        , updated_last_on
        , updated_last_by_user_id
		, change_set_id
	)
	SELECT DISTINCT
		  PLAYER.player_id
        , PLAYER.game_id
        , PLAYER.user_id
        , PLAYER.deck_id
        , PLAYER.name
        , PLAYER.notes
        , PLAYER.display_order
        , PLAYER.active
        , PLAYER.created_on
        , PLAYER.created_by_user_id
        , PLAYER.updated_last_on
        , PLAYER.updated_last_by_user_id
        , PLAYER.change_set_id
	FROM tcg.public.TCG_MTG_Game_Player PLAYER
	/*
    INNER JOIN Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
        ON  PLAYER.player_id = T_PLAYER_DAMAGE.player_id
        OR  PLAYER.player_id = T_PLAYER_DAMAGE.received_from_commander_player_id
    */
    INNER JOIN Temp_MTG_Round_Damage_Save_Game T_GAME ON PLAYER.game_id = T_GAME.game_id
	;
    
	/*
					INSERT INTO Temp_MTG_Round_Damage_Save_Error (
						  error_type_id
						, message
					)
					SELECT
						  v_bad_data_error_type_id -- error_type_id
						, CONCAT(
							'Rounds: '
							, STRING_AGG(T_ROUND.error_name, ', ')
							, '.'
						) -- message
					FROM Temp_MTG_Round_Damage_Save_Round T_ROUND
					;
	*/

    -- Validate Round
	-- Missing fields
	WITH Round_Missing_Field AS (
        SELECT
              T_ROUND.temp_id
            , 'game_id' AS field
        FROM Temp_MTG_Round_Damage_Save_Round T_ROUND
        WHERE T_ROUND.game_id IS NULL
    )
	INSERT INTO Temp_MTG_Round_Damage_Save_Error (
		  error_type_id
		, message
	)
	SELECT
		  v_bad_data_error_type_id -- error_type_id
		, CONCAT(
			'Missing mandatory field: '
			, ROUND_MISSING_FIELD.field
			, ' on '
			, T_ROUND.error_name
			, '.'
		) -- message
	FROM Temp_MTG_Round_Damage_Save_Round T_ROUND
	INNER JOIN Round_Missing_Field ROUND_MISSING_FIELD ON T_ROUND.temp_id = ROUND_MISSING_FIELD.temp_id
	;

	-- Failed join fields
	WITH Round_Failed_Join_Field AS (
        SELECT
              T_ROUND.temp_id
            , 'game_id' AS field
        FROM Temp_MTG_Round_Damage_Save_Round T_ROUND
        LEFT JOIN Temp_MTG_Round_Damage_Save_Game T_GAME ON T_ROUND.game_id = T_GAME.game_id
        WHERE T_GAME.game_id IS NULL
    )
	INSERT INTO Temp_MTG_Round_Damage_Save_Error (
		  error_type_id
		, message
	)
	SELECT
		  v_bad_data_error_type_id -- error_type_id
		, CONCAT(
			'Failed relationship: '
			, ROUND_FAILED_JOIN_FIELD.field
			, ' on '
			, T_ROUND.error_name
			, '.'
		) -- message
	FROM Temp_MTG_Round_Damage_Save_Round T_ROUND
	INNER JOIN Round_Failed_Join_Field ROUND_FAILED_JOIN_FIELD ON T_ROUND.temp_id = ROUND_FAILED_JOIN_FIELD.temp_id
	;

	-- Duplicate
	WITH 
		  Existing_Round AS (
			SELECT
				  TCG_ROUND.round_id
                , TCG_ROUND.game_id
                , TCG_ROUND.display_order
			FROM tcg.public.TCG_MTG_Game_Round TCG_ROUND
            LEFT JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND ON TCG_ROUND.round_id = T_ROUND.round_id
            WHERE
                    TCG_ROUND.active
				/*
				AND NOT EXISTS (
					SELECT 1
					FROM Temp_MTG_Round_Damage_Save_Round T_ROUND
					WHERE T_ROUND.round_id = TCG_ROUND.round_id
				)
				*/
				AND T_ROUND.temp_id IS NULL
		)
		, All_Round AS (
			SELECT
				  T_ROUND.temp_id
                , T_ROUND.game_id
                , T_ROUND.display_order
                , TRUE AS is_save_record
			FROM Temp_MTG_Round_Damage_Save_Round T_ROUND
            UNION
			SELECT
				  NULL AS temp_id
                , EXISTING_ROUND.game_id
                , EXISTING_ROUND.display_order
                , FALSE AS is_save_record
			FROM Existing_Round EXISTING_ROUND
		)
		, Unique_Game_Round AS (
			SELECT
				  ALL_ROUND.game_id
                , ALL_ROUND.display_order
                , COUNT(*) AS count_rounds
			FROM All_Round ALL_ROUND
            GROUP BY
                  ALL_ROUND.game_id
                , ALL_ROUND.display_order
		)
	UPDATE Temp_MTG_Round_Damage_Save_Round T_ROUND
	SET is_duplicate = CASE WHEN COALESCE(UNIQUE_GAME_ROUND.count_rounds, 0) > 1 THEN TRUE ELSE FALSE END
	FROM Unique_Game_Round UNIQUE_GAME_ROUND
	WHERE
            T_ROUND.game_id = UNIQUE_GAME_ROUND.game_id
        AND T_ROUND.display_order = UNIQUE_GAME_ROUND.display_order
	;
	
	IF EXISTS (
		SELECT *
		FROM Temp_MTG_Round_Damage_Save_Round T_ROUND
		WHERE T_ROUND.is_duplicate
		LIMIT 1
	) THEN
		INSERT INTO Temp_MTG_Round_Damage_Save_Error (
			  error_type_id
			, message
		)
		SELECT
			  v_bad_data_error_type_id -- error_type_id
			, CONCAT(
				  'Duplicate on '
				, T_ROUND.error_name
			) -- message
		FROM Temp_MTG_Round_Damage_Save_Round T_ROUND
		WHERE T_ROUND.is_duplicate
		;
	END IF;
    
    -- Validate Damage
	-- Missing fields
	WITH Player_Damage_Missing_Field AS (
        SELECT
              T_PLAYER_DAMAGE.temp_id
            , 'round_id' AS field
        FROM Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
        WHERE T_PLAYER_DAMAGE.round_id IS NULL
        UNION
        SELECT
              T_PLAYER_DAMAGE.temp_id
            , 'player_id' AS field
        FROM Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
        WHERE T_PLAYER_DAMAGE.player_id IS NULL
		/*
        UNION
        SELECT
              T_PLAYER_DAMAGE.temp_id
            , 'health_change' AS field
        FROM Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
        WHERE T_PLAYER_DAMAGE.health_change IS NULL
		UNION
        SELECT
              T_PLAYER_DAMAGE.temp_id
            , 'life_gain' AS field
        FROM Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
        WHERE T_PLAYER_DAMAGE.life_gain IS NULL
        UNION
        SELECT
              T_PLAYER_DAMAGE.temp_id
            , 'life_loss' AS field
        FROM Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
        WHERE T_PLAYER_DAMAGE.life_loss IS NULL
        UNION
        SELECT
              T_PLAYER_DAMAGE.temp_id
            , 'commander_deaths' AS field
        FROM Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
        WHERE T_PLAYER_DAMAGE.commander_deaths IS NULL
        */
    )
	INSERT INTO Temp_MTG_Round_Damage_Save_Error (
		  error_type_id
		, message
	)
	SELECT
		  v_bad_data_error_type_id -- error_type_id
		, CONCAT(
			'Missing mandatory field: '
			, PLAYER_DAMAGE_MISSING_FIELD.field
			, ' on '
			, T_PLAYER_DAMAGE.error_name
			, '.'
		) -- message
	FROM Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
	INNER JOIN Player_Damage_Missing_Field PLAYER_DAMAGE_MISSING_FIELD ON T_PLAYER_DAMAGE.temp_id = PLAYER_DAMAGE_MISSING_FIELD.temp_id
	;

	-- Failed join fields
	WITH Player_Failed_Join_Field AS (
        SELECT
              T_PLAYER_DAMAGE.temp_id
            , 'round_id' AS field
        FROM Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
        LEFT JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND ON T_PLAYER_DAMAGE.temp_round_id = T_ROUND.temp_id
        WHERE T_ROUND.round_id IS NULL
        UNION
        SELECT
              T_PLAYER_DAMAGE.temp_id
            , 'player_id' AS field
        FROM Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
        LEFT JOIN Temp_MTG_Round_Damage_Save_Player T_PLAYER ON T_PLAYER_DAMAGE.player_id = T_PLAYER.player_id
        WHERE T_PLAYER.player_id IS NULL
        UNION
        SELECT
              T_PLAYER_DAMAGE.temp_id
            , 'received_from_commander_player_id' AS field
        FROM Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
        LEFT JOIN Temp_MTG_Round_Damage_Save_Player T_PLAYER ON T_PLAYER_DAMAGE.received_from_commander_player_id = T_PLAYER.player_id
        WHERE
				T_PLAYER.player_id IS NULL
			AND T_PLAYER_DAMAGE.received_from_commander_player_id IS NOT NULL
    )
	INSERT INTO Temp_MTG_Round_Damage_Save_Error (
		  error_type_id
		, message
	)
	SELECT
		  v_bad_data_error_type_id -- error_type_id
		, CONCAT(
			'Failed relationship: '
			, PLAYER_FAILED_JOIN_FIELD.field
			, ' on '
			, T_PLAYER_DAMAGE.error_name
			, '.'
		) -- message
	FROM Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
	INNER JOIN Player_Failed_Join_Field PLAYER_FAILED_JOIN_FIELD ON T_PLAYER_DAMAGE.temp_id = PLAYER_FAILED_JOIN_FIELD.temp_id
	;

	-- Duplicate Round Player Damage
	WITH 
		  Existing_Player_Damage AS (
			SELECT
				  T_PLAYER_DAMAGE.round_id
                , T_PLAYER_DAMAGE.player_id
                , COALESCE(T_PLAYER_DAMAGE.received_from_commander_player_id, 0) AS received_from_commander_player_id
			FROM tcg.public.TCG_MTG_Game_Round_Player_Damage PLAYER_DAMAGE
            LEFT JOIN Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE ON PLAYER_DAMAGE.damage_id = T_PLAYER_DAMAGE.damage_id
            WHERE
                    T_PLAYER_DAMAGE.temp_id IS NULL
                AND PLAYER_DAMAGE.active
		)
		, All_Player_Damage AS (
			SELECT
				  T_PLAYER_DAMAGE.temp_id
                , T_PLAYER_DAMAGE.round_id
                , T_PLAYER_DAMAGE.player_id
                , COALESCE(T_PLAYER_DAMAGE.received_from_commander_player_id, 0) AS received_from_commander_player_id
                , TRUE AS is_save_record
			FROM Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
            UNION
			SELECT
				  NULL AS temp_id
                , EXISTING_PLAYER_DAMAGE.round_id
                , EXISTING_PLAYER_DAMAGE.player_id
                , EXISTING_PLAYER_DAMAGE.received_from_commander_player_id
                , FALSE AS is_save_record
			FROM Existing_Player_Damage EXISTING_PLAYER_DAMAGE
		)
		, Unique_Game_Player_Damage AS (
			SELECT
                  ALL_PLAYER_DAMAGE.round_id
                , ALL_PLAYER_DAMAGE.player_id
                , ALL_PLAYER_DAMAGE.received_from_commander_player_id
                , COUNT(*) AS count_damage
			FROM All_Player_Damage ALL_PLAYER_DAMAGE
            GROUP BY
                  ALL_PLAYER_DAMAGE.round_id
                , ALL_PLAYER_DAMAGE.player_id
                , ALL_PLAYER_DAMAGE.received_from_commander_player_id
		)
	UPDATE Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
	SET is_duplicate = CASE WHEN COALESCE(UNIQUE_PLAYER_DAMAGE.count_damage, 0) > 1 THEN TRUE ELSE FALSE END
	FROM Unique_Game_Player_Damage UNIQUE_PLAYER_DAMAGE
	WHERE
        	T_PLAYER_DAMAGE.round_id = UNIQUE_PLAYER_DAMAGE.round_id
        AND T_PLAYER_DAMAGE.player_id = UNIQUE_PLAYER_DAMAGE.player_id
        AND COALESCE(T_PLAYER_DAMAGE.received_from_commander_player_id, 0) = UNIQUE_PLAYER_DAMAGE.received_from_commander_player_id
	;
	
	IF EXISTS (
		SELECT *
		FROM Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
		WHERE T_PLAYER_DAMAGE.is_duplicate
		LIMIT 1
	) THEN
		INSERT INTO Temp_MTG_Round_Damage_Save_Error (
			  error_type_id
			, message
		)
		SELECT
			  v_bad_data_error_type_id -- error_type_id
			, CONCAT(
				  'Duplicate on '
				, T_PLAYER_DAMAGE.error_name
			) -- message
		FROM Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
		WHERE T_PLAYER_DAMAGE.is_duplicate
		;
	END IF;

	-- Get all missing rounds and damage records for games
	INSERT INTO Temp_MTG_Round_Damage_Save_Round (
		  temp_id
        , round_id
        , game_id
        , notes
        , display_order
        , active
        , created_on
        , created_by_user_id
        , updated_last_on
        , updated_last_by_user_id

		, is_new
		, error_name
	)
	SELECT
		  -TCG_ROUND.round_id
        , TCG_ROUND.round_id
        , TCG_ROUND.game_id
        , TCG_ROUND.notes
        , TCG_ROUND.display_order
        , TCG_ROUND.active
        , TCG_ROUND.created_on
        , TCG_ROUND.created_by_user_id
        , TCG_ROUND.updated_last_on
        , TCG_ROUND.updated_last_by_user_id

		, FALSE AS is_new
		, CONCAT(
			  'Round { id: '
			, CAST(TCG_ROUND.round_id AS VARCHAR)
			, ', temp id: '
			, CAST(NULL AS VARCHAR)
			, ', display order: '
			, CAST(TCG_ROUND.display_order AS VARCHAR)
			, ', game id: '
			, CAST(TCG_ROUND.game_id AS VARCHAR)
			, ' }'
		) -- error_name
	FROM tcg.public.TCG_MTG_Game_Round TCG_ROUND
	INNER JOIN Temp_MTG_Round_Damage_Save_Game T_GAME ON TCG_ROUND.game_id = T_GAME.game_id
	LEFT JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND ON TCG_ROUND.round_id = T_ROUND.round_id
	WHERE T_ROUND.round_id IS NULL
	;
	
	INSERT INTO Temp_MTG_Round_Damage_Save_Round_Player_Damage (
		  temp_id
        , damage_id
        , temp_round_id
        , round_id
        , player_id
        , received_from_commander_player_id
        , life_gain
        , life_loss
        , commander_deaths
		, is_eliminated
        , active
        , created_on
        , created_by_user_id
        , updated_last_on
        , updated_last_by_user_id

		, is_new
		, error_name
	)
	SELECT
		  -PLAYER_DAMAGE.damage_id
        , PLAYER_DAMAGE.damage_id
        , T_ROUND.temp_id AS temp_round_id
        , PLAYER_DAMAGE.round_id
        , PLAYER_DAMAGE.player_id
        , PLAYER_DAMAGE.received_from_commander_player_id
        , PLAYER_DAMAGE.life_gain
        , PLAYER_DAMAGE.life_loss
        , PLAYER_DAMAGE.commander_deaths
		, PLAYER_DAMAGE.is_eliminated
        , PLAYER_DAMAGE.active
        , PLAYER_DAMAGE.created_on
        , PLAYER_DAMAGE.created_by_user_id
        , PLAYER_DAMAGE.updated_last_on
        , PLAYER_DAMAGE.updated_last_by_user_id

		, FALSE AS is_new
		, CONCAT(
			  'Round Player Damage { id: '
			, CAST(PLAYER_DAMAGE.damage_id AS VARCHAR)
			, ', temp id: '
			, CAST(NULL AS VARCHAR)
			, ', round id: '
			, CAST(PLAYER_DAMAGE.round_id AS VARCHAR)
			, ', player id: '
			, CAST(PLAYER_DAMAGE.player_id AS VARCHAR)
			, ', received from commander player id: '
			, CAST(PLAYER_DAMAGE.received_from_commander_player_id AS VARCHAR)
			, ', life gain: '
			, CAST(PLAYER_DAMAGE.life_gain AS VARCHAR)
			, ', life loss: '
			, CAST(PLAYER_DAMAGE.life_loss AS VARCHAR)
			, ' }'
		) AS error_name
	FROM tcg.public.TCG_MTG_Game_Round_Player_Damage PLAYER_DAMAGE
	INNER JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND ON PLAYER_DAMAGE.round_id = T_ROUND.round_id
	LEFT JOIN Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE ON PLAYER_DAMAGE.damage_id = T_PLAYER_DAMAGE.damage_id
	WHERE T_PLAYER_DAMAGE.damage_id IS NULL
	;

    -- Calculations
    WITH
          Game_Length AS (
            SELECT
                  T_GAME.game_id
                , MAX(T_ROUND.display_order) AS max_round_display_order
            FROM Temp_MTG_Round_Damage_Save_Game T_GAME
            INNER JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND
                ON  T_GAME.game_id = T_ROUND.game_id
                AND T_ROUND.active
            GROUP BY T_GAME.game_id
        )
        , Game_Size AS (
            SELECT
                  T_GAME.game_id
                , COUNT(*) AS count_players
            FROM Temp_MTG_Round_Damage_Save_Game T_GAME
            INNER JOIN Temp_MTG_Round_Damage_Save_Player T_PLAYER
                ON  T_GAME.game_id = T_PLAYER.game_id
                AND T_PLAYER.active
            GROUP BY T_GAME.game_id
        )
        , Game_Combined AS (
            SELECT
                  T_GAME.game_id
                , GAME_LENGTH.max_round_display_order
                , GAME_SIZE.count_players
            FROM Temp_MTG_Round_Damage_Save_Game T_GAME
            LEFT JOIN Game_Length GAME_LENGTH ON T_GAME.game_id = GAME_LENGTH.game_id
            LEFT JOIN Game_Size GAME_SIZE ON T_GAME.game_id = GAME_SIZE.game_id
        )
    UPDATE Temp_MTG_Round_Damage_Save_Game T_GAME
    SET
          max_round_display_order = COALESCE(GAME_COMBINED.max_round_display_order, 0)
        , count_players = COALESCE(GAME_COMBINED.count_players, 0)
        , duration = CASE
            WHEN
                    T_GAME.start_on IS NOT NULL
                AND T_GAME.end_on IS NOT NULL
            THEN T_GAME.end_on - T_GAME.start_on
            ELSE NULL
        END
    FROM Game_Combined GAME_COMBINED
    WHERE T_GAME.game_id = GAME_COMBINED.game_id
    ;

    WITH
          All_Player_Round AS (
            SELECT
                  T_ROUND.game_id
                , T_PLAYER.player_id
                , T_ROUND.round_id
            FROM Temp_MTG_Round_Damage_Save_Round T_ROUND
            -- INNER JOIN Temp_MTG_Round_Damage_Save_Game T_GAME ON T_ROUND.game_id = T_GAME.game_id
            CROSS JOIN Temp_MTG_Round_Damage_Save_Player T_PLAYER -- ON T_ROUND.game_id = T_PLAYER.game_id
            WHERE
                    T_ROUND.active
                AND T_PLAYER.active
        )
        , Player_Round_Commander_Damage_Received AS (
            SELECT
                  ALL_PLAYER_ROUND.game_id
                , ALL_PLAYER_ROUND.player_id
                , ALL_PLAYER_ROUND.round_id
        
                , SUM(T_PLAYER_DAMAGE.life_loss) AS total_commander_damage_received
            FROM All_Player_Round ALL_PLAYER_ROUND
            INNER JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND_PLAYER ON ALL_PLAYER_ROUND.round_id = T_ROUND_PLAYER.round_id
            INNER JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND_DAMAGE
                ON  T_ROUND_PLAYER.game_id = T_ROUND_DAMAGE.game_id
                AND T_ROUND_PLAYER.display_order >= T_ROUND_DAMAGE.display_order
            INNER JOIN Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
                ON  T_ROUND_DAMAGE.round_id = T_PLAYER_DAMAGE.round_id
                AND ALL_PLAYER_ROUND.player_id = T_PLAYER_DAMAGE.player_id
                AND T_PLAYER_DAMAGE.received_from_commander_player_id IS NOT NULL
            GROUP BY
                  ALL_PLAYER_ROUND.game_id
                , ALL_PLAYER_ROUND.player_id
                , ALL_PLAYER_ROUND.round_id
                -- , ALL_PLAYER_ROUND.received_from_commander_player_id
        )
        , Player_Round_Max_Commander_Damage_Received AS (
            SELECT
                  PLAYER_ROUND_COMMANDER_DAMAGE_IN.game_id
                , PLAYER_ROUND_COMMANDER_DAMAGE_IN.player_id
                , PLAYER_ROUND_COMMANDER_DAMAGE_IN.round_id
        
                , MAX(PLAYER_ROUND_COMMANDER_DAMAGE_IN.total_commander_damage_received) AS max_total_commander_damage_received
            FROM Player_Round_Commander_Damage_Received PLAYER_ROUND_COMMANDER_DAMAGE_IN
            GROUP BY
                  PLAYER_ROUND_COMMANDER_DAMAGE_IN.game_id
                , PLAYER_ROUND_COMMANDER_DAMAGE_IN.player_id
                , PLAYER_ROUND_COMMANDER_DAMAGE_IN.round_id
        )
        , Player_Round_Total_Commander_Damage_Dealt AS (
            SELECT
                  ALL_PLAYER_ROUND.game_id
                , ALL_PLAYER_ROUND.player_id
                , ALL_PLAYER_ROUND.round_id
        
                , SUM(T_PLAYER_DAMAGE.life_loss) AS total_commander_damage_dealt
            FROM All_Player_Round ALL_PLAYER_ROUND
            INNER JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND_PLAYER ON ALL_PLAYER_ROUND.round_id = T_ROUND_PLAYER.round_id
            INNER JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND_DAMAGE
                -- ON ALL_PLAYER_ROUND.round_id = T_ROUND_DAMAGE.round_id
                ON  T_ROUND_PLAYER.game_id = T_ROUND_DAMAGE.game_id
                AND T_ROUND_PLAYER.display_order >= T_ROUND_DAMAGE.display_order
            INNER JOIN Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
                ON  T_ROUND_DAMAGE.round_id = T_PLAYER_DAMAGE.round_id
                AND ALL_PLAYER_ROUND.player_id = T_PLAYER_DAMAGE.received_from_commander_player_id
            GROUP BY
                  ALL_PLAYER_ROUND.game_id
                , ALL_PLAYER_ROUND.player_id
                , ALL_PLAYER_ROUND.round_id
        )
        , Player_Round_Damage AS (
            SELECT
                  ALL_PLAYER_ROUND.game_id
                , ALL_PLAYER_ROUND.player_id
                , ALL_PLAYER_ROUND.round_id
        
                , SUM(T_PLAYER_DAMAGE.life_loss) AS total_damage_received
            FROM All_Player_Round ALL_PLAYER_ROUND
            INNER JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND_PLAYER ON ALL_PLAYER_ROUND.round_id = T_ROUND_PLAYER.round_id
            INNER JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND_DAMAGE
                -- ON ALL_PLAYER_ROUND.round_id = T_ROUND_DAMAGE.round_id
                ON  T_ROUND_PLAYER.game_id = T_ROUND_DAMAGE.game_id
                AND T_ROUND_PLAYER.display_order >= T_ROUND_DAMAGE.display_order
            INNER JOIN Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
                ON  T_ROUND_DAMAGE.round_id = T_PLAYER_DAMAGE.round_id
                AND ALL_PLAYER_ROUND.player_id = T_PLAYER_DAMAGE.player_id
                AND T_PLAYER_DAMAGE.life_loss > 0
            GROUP BY
                  ALL_PLAYER_ROUND.game_id
                , ALL_PLAYER_ROUND.player_id
                , ALL_PLAYER_ROUND.round_id
        )
        , Player_Round_Eliminated AS (
            SELECT
                  ALL_PLAYER_ROUND.game_id
                , ALL_PLAYER_ROUND.player_id
                , ALL_PLAYER_ROUND.round_id
        
                , BOOL_OR(T_PLAYER_DAMAGE.is_eliminated) AS is_eliminated
                , SUM(T_PLAYER_DAMAGE.commander_deaths) AS total_commander_deaths
            FROM All_Player_Round ALL_PLAYER_ROUND
            INNER JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND_PLAYER ON ALL_PLAYER_ROUND.round_id = T_ROUND_PLAYER.round_id
            INNER JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND_DAMAGE
                ON  T_ROUND_PLAYER.game_id = T_ROUND_DAMAGE.game_id
                AND T_ROUND_PLAYER.display_order >= T_ROUND_DAMAGE.display_order
            INNER JOIN Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
                ON  T_ROUND_DAMAGE.round_id = T_PLAYER_DAMAGE.round_id
                AND ALL_PLAYER_ROUND.player_id = T_PLAYER_DAMAGE.player_id
            GROUP BY
                  ALL_PLAYER_ROUND.game_id
                , ALL_PLAYER_ROUND.player_id
                , ALL_PLAYER_ROUND.round_id
        )
        , Player_Round_Total_Life AS (
            SELECT
                  ALL_PLAYER_ROUND.game_id
                , ALL_PLAYER_ROUND.player_id
                , ALL_PLAYER_ROUND.round_id
        
                , SUM(T_PLAYER_DAMAGE.life_gain) AS total_life_gained
            FROM All_Player_Round ALL_PLAYER_ROUND
            INNER JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND_PLAYER ON ALL_PLAYER_ROUND.round_id = T_ROUND_PLAYER.round_id
            INNER JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND_DAMAGE
                -- ON ALL_PLAYER_ROUND.round_id = T_ROUND_DAMAGE.round_id
                ON  T_ROUND_PLAYER.game_id = T_ROUND_DAMAGE.game_id
                AND T_ROUND_PLAYER.display_order >= T_ROUND_DAMAGE.display_order
            INNER JOIN Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
                ON  T_ROUND_DAMAGE.round_id = T_PLAYER_DAMAGE.round_id
                AND ALL_PLAYER_ROUND.player_id = T_PLAYER_DAMAGE.player_id
                AND T_PLAYER_DAMAGE.life_gain > 0
            GROUP BY
                  ALL_PLAYER_ROUND.game_id
                , ALL_PLAYER_ROUND.player_id
                , ALL_PLAYER_ROUND.round_id
        )
    INSERT INTO Temp_MTG_Round_Damage_Save_Player_Round_Link (
          game_id
        , player_id
        , round_id
        
        , max_total_commander_damage_received
        , total_commander_damage_dealt
        , total_damage_received
        , is_eliminated
        , total_commander_deaths
        , total_life_gained
    )
    SELECT
          ALL_PLAYER_ROUND.game_id
        , ALL_PLAYER_ROUND.player_id
        , ALL_PLAYER_ROUND.round_id

        , COALESCE(PLAYER_ROUND_MAX_CDR_DAMAGE_IN.max_total_commander_damage_received, 0) AS max_total_commander_damage_received
        , COALESCE(PLAYER_ROUND_TOTAL_CDR_DAMAGE_OUT.total_commander_damage_dealt, 0) AS total_commander_damage_dealt
        , COALESCE(PLAYER_ROUND_TOTAL_DAMAGE.total_damage_received, 0) AS total_damage_received
        , COALESCE(PLAYER_ROUND_ELIMINATED.is_eliminated, FALSE) AS is_eliminated
        , COALESCE(PLAYER_ROUND_ELIMINATED.total_commander_deaths, 0) AS total_commander_deaths
        , COALESCE(PLAYER_ROUND_TOTAL_LIFE.total_life_gained, 0) AS total_life_gained
    FROM All_Player_Round ALL_PLAYER_ROUND
    LEFT JOIN Player_Round_Max_Commander_Damage_Received PLAYER_ROUND_MAX_CDR_DAMAGE_IN
        ON  ALL_PLAYER_ROUND.round_id = PLAYER_ROUND_MAX_CDR_DAMAGE_IN.round_id
        AND ALL_PLAYER_ROUND.player_id = PLAYER_ROUND_MAX_CDR_DAMAGE_IN.player_id
    LEFT JOIN Player_Round_Total_Commander_Damage_Dealt PLAYER_ROUND_TOTAL_CDR_DAMAGE_OUT
        ON  ALL_PLAYER_ROUND.round_id = PLAYER_ROUND_TOTAL_CDR_DAMAGE_OUT.round_id
        AND ALL_PLAYER_ROUND.player_id = PLAYER_ROUND_TOTAL_CDR_DAMAGE_OUT.player_id
    LEFT JOIN Player_Round_Damage PLAYER_ROUND_TOTAL_DAMAGE
        ON  ALL_PLAYER_ROUND.round_id = PLAYER_ROUND_TOTAL_DAMAGE.round_id
        AND ALL_PLAYER_ROUND.player_id = PLAYER_ROUND_TOTAL_DAMAGE.player_id
    LEFT JOIN Player_Round_Eliminated PLAYER_ROUND_ELIMINATED
        ON  ALL_PLAYER_ROUND.round_id = PLAYER_ROUND_ELIMINATED.round_id
        AND ALL_PLAYER_ROUND.player_id = PLAYER_ROUND_ELIMINATED.player_id
    LEFT JOIN Player_Round_Total_Life PLAYER_ROUND_TOTAL_LIFE
        ON  ALL_PLAYER_ROUND.round_id = PLAYER_ROUND_TOTAL_LIFE.round_id
        AND ALL_PLAYER_ROUND.player_id = PLAYER_ROUND_TOTAL_LIFE.player_id
    ;

    WITH
          Player_Round_Eliminated AS (
            SELECT
                  T_PLAYER_ROUND_LINK.player_id
                , T_GAME.game_id
                , T_GAME.max_round_display_order AS game_max_round_display_order
                , MIN(T_ROUND.display_order) AS round_display_order
            FROM Temp_MTG_Round_Damage_Save_Player_Round_Link T_PLAYER_ROUND_LINK
            INNER JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND ON T_PLAYER_ROUND_LINK.round_id = T_ROUND.round_id
            INNER JOIN Temp_MTG_Round_Damage_Save_Game T_GAME ON T_PLAYER_ROUND_LINK.game_id = T_GAME.game_id
            WHERE
                    T_PLAYER_ROUND_LINK.max_total_commander_damage_received >= v_commander_damage_limit
                OR  T_PLAYER_ROUND_LINK.total_damage_received >= T_GAME.starting_life + T_PLAYER_ROUND_LINK.total_life_gained
                OR  T_PLAYER_ROUND_LINK.is_eliminated
            GROUP BY
                  T_PLAYER_ROUND_LINK.player_id
                , T_GAME.game_id
                , T_GAME.max_round_display_order
        )
        , Player_Round_Final AS (
            SELECT
                  PLAYER_ROUND_ELIMINATED.player_id
                , PLAYER_ROUND_ELIMINATED.round_display_order AS round_display_order_eliminated
                , COALESCE(
                      PLAYER_ROUND_ELIMINATED.round_display_order
                    , PLAYER_ROUND_ELIMINATED.game_max_round_display_order
                ) AS final_player_damage_round_display_order
                , T_ROUND_FINAL.round_id AS final_player_damage_round_id
                , RANK() OVER (
                    PARTITION BY PLAYER_ROUND_ELIMINATED.game_id
                    ORDER BY COALESCE(
                          PLAYER_ROUND_ELIMINATED.round_display_order
                        , PLAYER_ROUND_ELIMINATED.game_max_round_display_order + 1
                    )
                ) AS placement
            FROM Player_Round_Eliminated PLAYER_ROUND_ELIMINATED
            INNER JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND_FINAL
                ON  COALESCE(
                      PLAYER_ROUND_ELIMINATED.round_display_order
                    , PLAYER_ROUND_ELIMINATED.game_max_round_display_order + 1
                ) = T_ROUND_FINAL.display_order
                AND PLAYER_ROUND_ELIMINATED.game_id = T_ROUND_FINAL.game_id
                AND T_ROUND_FINAL.active
        )
        , Player_Final_Round_Aggregated AS (
            SELECT
                  PLAYER_ROUND_FINAL.player_id
                , MAX(T_PLAYER_ROUND_LINK.max_total_commander_damage_received) AS max_total_commander_damage_received
                , SUM(T_PLAYER_ROUND_LINK.total_commander_damage_dealt) AS total_commander_damage_dealt
                , SUM(T_PLAYER_ROUND_LINK.total_damage_received) AS total_damage_received
                , SUM(T_PLAYER_ROUND_LINK.total_commander_deaths) AS total_commander_deaths
                , SUM(T_PLAYER_ROUND_LINK.total_life_gained) AS total_life_gained
            FROM Player_Round_Final PLAYER_ROUND_FINAL -- Player_Round_Eliminated PLAYER_ROUND_ELIMINATED
            INNER JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND ON PLAYER_ROUND_FINAL.final_player_damage_round_id = T_ROUND.round_id
            INNER JOIN Temp_MTG_Round_Damage_Save_Player_Round_Link T_PLAYER_ROUND_LINK 
                ON  PLAYER_ROUND_FINAL.player_id = T_PLAYER_ROUND_LINK.player_id
                AND PLAYER_ROUND_FINAL.final_player_damage_round_id = T_PLAYER_ROUND_LINK.round_id
            GROUP BY PLAYER_ROUND_FINAL.player_id
        )
    UPDATE Temp_MTG_Round_Damage_Save_Player T_PLAYER
    SET
          round_display_order_eliminated = PLAYER_ROUND_FINAL.round_display_order_eliminated
        , final_player_damage_round_id = PLAYER_ROUND_FINAL.final_player_damage_round_id
        , placement = PLAYER_ROUND_FINAL.placement
        , max_total_commander_damage_received = PLAYER_FINAL_ROUND_AGGREGATED.max_total_commander_damage_received
        , total_commander_damage_dealt = PLAYER_FINAL_ROUND_AGGREGATED.total_commander_damage_dealt
        , total_damage_received = PLAYER_FINAL_ROUND_AGGREGATED.total_damage_received
        , total_life_gained = PLAYER_FINAL_ROUND_AGGREGATED.total_life_gained
    /*
    FROM Player_Placement PLAYER_PLACEMENT
    INNER JOIN Player_Final_Round_Aggregated PLAYER_FINAL_ROUND_AGGREGATED ON PLAYER_PLACEMENT.player_id = PLAYER_FINAL_ROUND_AGGREGATED.player_id
    WHERE T_PLAYER.player_id = PLAYER_PLACEMENT.player_id
    */
    FROM Player_Round_Final PLAYER_ROUND_FINAL
    INNER JOIN Player_Final_Round_Aggregated PLAYER_FINAL_ROUND_AGGREGATED ON PLAYER_ROUND_FINAL.player_id = PLAYER_FINAL_ROUND_AGGREGATED.player_id
    WHERE T_PLAYER.player_id = PLAYER_ROUND_FINAL.player_id
    ;

    WITH
        Round_Survivor AS (
            SELECT
                  T_PLAYER_ROUND_LINK.round_id
                , COUNT(*) AS count_survivors
            FROM Temp_MTG_Round_Damage_Save_Player_Round_Link T_PLAYER_ROUND_LINK
			INNER JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND ON T_PLAYER_ROUND_LINK.round_id = T_ROUND.round_id
			INNER JOIN Temp_MTG_Round_Damage_Save_Game T_GAME ON T_ROUND.game_id = T_GAME.game_id
            WHERE
                    T_PLAYER_ROUND_LINK.max_total_commander_damage_received < v_commander_damage_limit
                AND T_PLAYER_ROUND_LINK.total_damage_received < T_GAME.starting_life + T_PLAYER_ROUND_LINK.total_life_gained
                AND NOT T_PLAYER_ROUND_LINK.is_eliminated
            GROUP BY T_PLAYER_ROUND_LINK.round_id
        )
        , All_Round_Survivor AS (
            SELECT
                  T_ROUND.round_id
                , COALESCE(ROUND_SURVIVOR.count_survivors, 0) AS count_survivors
            FROM Temp_MTG_Round_Damage_Save_Round T_ROUND
			LEFT JOIN Round_Survivor ROUND_SURVIVOR ON T_ROUND.round_id = ROUND_SURVIVOR.round_id
        )
    UPDATE Temp_MTG_Round_Damage_Save_Round T_ROUND
    SET
          count_survivors = ALL_ROUND_SURVIVOR.count_survivors
    FROM All_Round_Survivor ALL_ROUND_SURVIVOR
    WHERE T_ROUND.round_id = ALL_ROUND_SURVIVOR.round_id
    ;

    UPDATE Temp_MTG_Round_Damage_Save_Game T_GAME
    SET end_on = COALESCE(T_GAME.end_on, v_time_start)
    FROM Temp_MTG_Round_Damage_Save_Round T_ROUND
    WHERE
            T_GAME.game_id = T_ROUND.game_id
        AND T_ROUND.count_survivors <= 1
		AND T_ROUND.active
    ;

    WITH
        Game_Final_Round AS (
            SELECT
                T_ROUND.game_id
                , MIN(T_ROUND.display_order) AS final_round_display_order
            FROM Temp_MTG_Round_Damage_Save_Round T_ROUND
            WHERE
					T_ROUND.count_survivors <= 1
				AND T_ROUND.active
            GROUP BY T_ROUND.game_id
        )
		, Game_Latest_Round AS (
            SELECT
                  GAME_FINAL_ROUND.game_id
                , GAME_FINAL_ROUND.final_round_display_order
				, TRUE AS Is_Completed
            FROM Game_Final_Round GAME_FINAL_ROUND
			UNION
            SELECT
                  T_ROUND.game_id
                , MAX(T_ROUND.display_order) AS final_round_display_order
				, FALSE AS is_completed
            FROM Temp_MTG_Round_Damage_Save_Round T_ROUND
			LEFT JOIN Game_Final_Round GAME_FINAL_ROUND ON T_ROUND.game_id = GAME_FINAL_ROUND.game_id
            WHERE
					T_ROUND.count_survivors > 1
				AND GAME_FINAL_ROUND.game_id IS NULL
				AND T_ROUND.active
            GROUP BY T_ROUND.game_id
        )
    UPDATE Temp_MTG_Round_Damage_Save_Game T_GAME
    SET end_on = CASE WHEN GAME_LATEST_ROUND.is_completed
		THEN COALESCE(T_GAME.end_on, v_time_start)
		ELSE NULL
	END
    FROM Game_Latest_Round GAME_LATEST_ROUND
    WHERE T_GAME.game_id = GAME_LATEST_ROUND.game_id
	;

	-- Nothing to save
	IF  (
            NOT EXISTS (SELECT * FROM Temp_MTG_Round_Damage_Save_Round LIMIT 1)
        AND NOT EXISTS (SELECT * FROM Temp_MTG_Round_Damage_Save_Round_Player_Damage LIMIT 1)
    ) THEN
		INSERT INTO Temp_MTG_Round_Damage_Save_Error (
			  error_type_id
			, message
		)
		VALUES (
			  v_warning_error_type_id
			, 'Nothing to save.'
		);
	END IF;

	/*
		INSERT INTO Temp_MTG_Round_Damage_Save_Error (
			  error_type_id
			, message
		)
		SELECT
			  v_warning_error_type_id AS error_type_id
			, CONCAT(
				'Games: '
				, STRING_AGG(CONCAT(
					'Id: '
					, CAST(T_GAME.game_id AS TEXT)
					, ', End: '
					, CAST(T_GAME.end_on AS TEXT)
				), ', ')
			) AS message
		FROM Temp_MTG_Round_Damage_Save_Game T_GAME
		UNION
		VALUES (
			  v_warning_error_type_id -- AS error_type_id
			, CONCAT(
				  'Count games: '
				, (SELECT COUNT(*) FROM Temp_MTG_Round_Damage_Save_Game T_GAME)
			) -- AS message
		)
		UNION
		SELECT
			  v_warning_error_type_id AS error_type_id
			, CONCAT(
				'Rounds: '
				, STRING_AGG(CONCAT(
					'{ Id: '
					, CAST(T_ROUND.round_id AS TEXT)
					, ', Display order: '
					, CAST(T_ROUND.display_order AS TEXT)
					, ', Survivors: '
					, CAST(T_ROUND.count_survivors AS TEXT)
					, '}'
				), ', ')
			) AS message
		FROM Temp_MTG_Round_Damage_Save_Round T_ROUND
		UNION
		SELECT
			  v_warning_error_type_id AS error_type_id
			, CONCAT(
				'Round Player Links: '
				, STRING_AGG(CONCAT(
					 ' Round Player Link: { '
			        , 'game_id: '
			        , game_id::TEXT
			        , ', player id: '
			        , player_id::TEXT
			        , ', round id: '
			        , round_id::TEXT
			        
			        , ', max_total_commander_damage_received: '
			        , max_total_commander_damage_received::TEXT
			        , ', total_commander_damage_dealt: '
			        , total_commander_damage_dealt::TEXT
			        , ', total_damage_received: '
			        , total_damage_received::TEXT
			        , ', is_eliminated: '
			        , is_eliminated::TEXT
			        , ', total_commander_deaths: '
			        , total_commander_deaths::TEXT
			        , ', total_life_gained: '
					, total_life_gained::TEXT
					, ' }'
				), ', ')
			)
		FROM Temp_MTG_Round_Damage_Save_Player_Round_Link T_PLAYER_ROUND
		;
	*/

	-- Outputs
	/*
	INSERT INTO Temp_MTG_Round_Damage_Save_Error (
		  error_type_id
		, message
	)
	VALUES
		(
			  v_bad_data_error_type_id -- error_type_id
			, CONCAT(
				'Temp round ids: '
				, (SELECT STRING_AGG(CAST(T_ROUND.temp_id AS VARCHAR), ',') FROM Temp_MTG_Round_Damage_Save_Round T_ROUND)
			) -- message
		)
		, (
			  v_bad_data_error_type_id -- error_type_id
			, CONCAT(
				'Temp player damage ids: '
				, (SELECT STRING_AGG(CAST(T_PLAYER_DAMAGE.temp_id AS VARCHAR), ',') FROM Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE)
			) -- message
		)
		, (
			  v_bad_data_error_type_id -- error_type_id
			, CONCAT(
				'Temp player ids: '
				, (SELECT STRING_AGG(CAST(T_PLAYER.player_id AS VARCHAR), ',') FROM Temp_MTG_Round_Damage_Save_Player T_PLAYER)
			) -- message
		)
		, (
			  v_bad_data_error_type_id -- error_type_id
			, CONCAT(
				'Temp game ids: '
				, (SELECT STRING_AGG(CAST(T_GAME.game_id AS VARCHAR), ',') FROM Temp_MTG_Round_Damage_Save_Game T_GAME)
			) -- message
		)
		, (
			  v_bad_data_error_type_id -- error_type_id
			, CONCAT(
				'Query player damage ids: '
				, (
					SELECT STRING_AGG(CAST(T_PLAYER_DAMAGE.temp_id AS VARCHAR), ',')
					FROM Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
			        INNER JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND ON T_PLAYER_DAMAGE.temp_round_id = T_ROUND.temp_id
			        LEFT JOIN Temp_MTG_Round_Damage_Save_Game T_GAME ON T_ROUND.game_id = T_GAME.game_id
			        LEFT JOIN Temp_MTG_Round_Damage_Save_Player T_PLAYER ON T_PLAYER_DAMAGE.player_id = T_PLAYER.player_id
				)
			) -- message
		)
	;
	*/

	-- Change Set
	INSERT INTO tcg.public.TCG_Change_Set (
		  comment
		, updated_last_by_user_id
	)
	VALUES (
		  v_comment
		, v_user_id
	)
	RETURNING change_set_id INTO v_change_set_id
	;

	-- 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
		  v_guid
		, T_ERROR.error_type_id
		, T_ERROR.message
		, T_ERROR.temp_id
		, v_time_start
		, v_user_id
		, v_time_start
		, v_user_id
		, v_change_set_id
	FROM Temp_MTG_Round_Damage_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
	;
	
	IF NOT EXISTS (SELECT * FROM Temp_MTG_Round_Damage_Save_Error T_ERROR WHERE T_ERROR.error_type_id <> v_warning_error_type_id LIMIT 1) THEN
		
		-- Set game updated last on
		UPDATE tcg.public.TCG_MTG_Game TCG_GAME
		SET
              end_on = T_GAME.end_on
			, updated_last_on = v_time_start
			, updated_last_by_user_id = v_user_id
		    , change_set_id = v_change_set_id
		FROM Temp_MTG_Round_Damage_Save_Game T_GAME
        -- Temp_MTG_Round_Damage_Save_Round T_ROUND
		WHERE TCG_GAME.game_id = T_GAME.game_id
		;

		-- Round
		INSERT INTO tcg.public.TCG_MTG_Game_Round (
              game_id
            , notes
            , display_order
            , active
            , created_on
            , created_by_user_id
            , updated_last_on
            , updated_last_by_user_id
            , change_set_id
		)
		SELECT
			  T_ROUND.game_id
            , T_ROUND.notes
            , T_ROUND.display_order
		    , T_ROUND.active
			, v_time_start -- created_on
			, v_user_id -- created_by_user_id
			, v_time_start -- updated_last_on
			, v_user_id -- updated_last_by_user_id
		    , v_change_set_id -- change_set_id
		FROM Temp_MTG_Round_Damage_Save_Round T_ROUND
        LEFT JOIN Temp_MTG_Round_Damage_Save_Game T_GAME ON T_ROUND.game_id = T_GAME.game_id
		WHERE
				T_ROUND.is_new = TRUE
			AND T_ROUND.active = TRUE
		ORDER BY
              T_GAME.created_on
            , T_ROUND.display_order
		;
	
		UPDATE tcg.public.TCG_MTG_Game_Round TCG_ROUND
		SET
              game_id = T_ROUND.game_id
            , notes = T_ROUND.notes
            , display_order = T_ROUND.display_order
		    , active = T_ROUND.active
			, updated_last_on = v_time_start
			, updated_last_by_user_id = v_user_id
		    , change_set_id = v_change_set_id
		FROM Temp_MTG_Round_Damage_Save_Round T_ROUND
		WHERE
				TCG_ROUND.round_id = T_ROUND.round_id
			AND NOT T_ROUND.is_new
		;

        UPDATE Temp_MTG_Round_Damage_Save_Round T_ROUND
        SET round_id = TCG_ROUND.round_id
        FROM tcg.public.TCG_MTG_Game_Round TCG_ROUND
        WHERE
                T_ROUND.game_id = TCG_ROUND.game_id
            AND T_ROUND.display_order = TCG_ROUND.display_order
            AND T_ROUND.is_new
        ;

		-- Round Player Damage
		INSERT INTO tcg.public.TCG_MTG_Game_Round_Player_Damage (
              round_id
            , player_id
            , received_from_commander_player_id
            , life_gain
            , life_loss
            , commander_deaths
			, is_eliminated
            , active
            , created_on
            , created_by_user_id
            , updated_last_on
            , updated_last_by_user_id
            , change_set_id
		)
		SELECT
			  T_ROUND.round_id
            , T_PLAYER_DAMAGE.player_id
            , T_PLAYER_DAMAGE.received_from_commander_player_id
		    , T_PLAYER_DAMAGE.life_gain
		    , T_PLAYER_DAMAGE.life_loss
		    , T_PLAYER_DAMAGE.commander_deaths
			, T_PLAYER_DAMAGE.is_eliminated
		    , T_PLAYER_DAMAGE.active
			, v_time_start -- created_on
			, v_user_id -- created_by_user_id
			, v_time_start -- updated_last_on
			, v_user_id -- updated_last_by_user_id
		    , v_change_set_id -- change_set_id 
		FROM Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
        INNER JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND ON T_PLAYER_DAMAGE.temp_round_id = T_ROUND.temp_id
        LEFT JOIN Temp_MTG_Round_Damage_Save_Game T_GAME ON T_ROUND.game_id = T_GAME.game_id
        LEFT JOIN Temp_MTG_Round_Damage_Save_Player T_PLAYER ON T_PLAYER_DAMAGE.player_id = T_PLAYER.player_id
		WHERE
				T_PLAYER_DAMAGE.is_new = TRUE
			AND T_PLAYER_DAMAGE.active = TRUE
		ORDER BY
              T_GAME.created_on
			, T_ROUND.display_order
			, T_PLAYER.display_order
		;
	
		UPDATE tcg.public.TCG_MTG_Game_Round_Player_Damage PLAYER_DAMAGE
		SET
              round_id = T_ROUND.round_id
            , player_id = T_PLAYER_DAMAGE.player_id
            , received_from_commander_player_id = T_PLAYER_DAMAGE.received_from_commander_player_id
		    , life_gain = T_PLAYER_DAMAGE.life_gain
		    , life_loss = T_PLAYER_DAMAGE.life_loss
		    , commander_deaths = T_PLAYER_DAMAGE.commander_deaths
			, is_eliminated = T_PLAYER_DAMAGE.is_eliminated
		    , active = T_PLAYER_DAMAGE.active
			, updated_last_on = v_time_start
			, updated_last_by_user_id = v_user_id
		    , change_set_id = v_change_set_id
		FROM Temp_MTG_Round_Damage_Save_Round_Player_Damage T_PLAYER_DAMAGE
        INNER JOIN Temp_MTG_Round_Damage_Save_Round T_ROUND ON T_PLAYER_DAMAGE.temp_round_id = T_ROUND.temp_id
		WHERE
				PLAYER_DAMAGE.damage_id = T_PLAYER_DAMAGE.damage_id
			AND NOT T_PLAYER_DAMAGE.is_new
		;
	END IF;

    COMMIT;
	
	o_success := NOT EXISTS (
		SELECT *
		FROM Temp_MTG_Round_Damage_Save_Error T_ERROR
		WHERE T_ERROR.error_type_id <> v_warning_error_type_id
		LIMIT 1
	);
	
	-- DELETE FROM tcg.public.TCG_MTG_Game_Round_Temp ROUND_T WHERE ROUND_T.guid = v_guid;
	-- DELETE FROM tcg.public.TCG_MTG_Game_Round_Player_Damage_Temp ROUND_DAMAGE_T WHERE ROUND_DAMAGE_T.guid = v_guid;

	DROP TABLE IF EXISTS Temp_MTG_Round_Damage_Save_Game;
	DROP TABLE IF EXISTS Temp_MTG_Round_Damage_Save_Player;
	DROP TABLE IF EXISTS Temp_MTG_Round_Damage_Save_Round;
	DROP TABLE IF EXISTS Temp_MTG_Round_Damage_Save_Round_Player_Damage;
	DROP TABLE IF EXISTS Temp_MTG_Round_Damage_Save_Error;
END;
$$;

-- Call it with:
DO $$
DECLARE
	v_comment TEXT := 'MTG Game Round Player Damage Save.';
	v_guid UUID;
    v_user_id INT := 3;
    v_success BOOLEAN;
BEGIN
	v_guid := '3935de65-d9a6-401b-9c6a-79f99e8d0642'::UUID; -- gen_random_uuid(); -- '6307bed6-73a1-41ab-9a90-79e18e14dd81'::UUID;
/*
	INSERT INTO tcg.public.TCG_MTG_Game_Round_Temp (
		  guid
	    , round_id
        , game_id
        , notes
        , display_order
        , active
	)
	VALUES (
          v_guid -- guid
        , -1 -- round_id
        , 4 -- game_id
        , 'Beaten' -- notes
        , 5 -- display_order
        , TRUE -- active
    )
    ;

	INSERT INTO tcg.public.TCG_MTG_Game_Round_Player_Damage_Temp (
		  guid
        , damage_id
        , round_id
        , player_id
        , received_from_commander_player_id
        -- , health_change
        , life_gain
        , life_loss
        , commander_deaths
        , active
	)
	VALUES
          (
              v_guid -- guid
            , NULL -- damage_id
            , -1 -- round_id
            , 3 -- player_id
            , NULL -- received_from_commander_player_id
            -- , -4 -- health_change
            , 0 -- life_gain
            , 4 -- life_loss
            , 1 -- commander_deaths
            , TRUE -- active
        )
		, (
              v_guid -- guid
            , NULL -- damage_id
            , -1 -- round_id
            , 3 -- player_id
            , 2 -- received_from_commander_player_id
            -- , -5 -- health_change
            , 0 -- life_gain
            , 5 -- life_loss
            , NULL -- commander_deaths
            , TRUE -- active
        )
		, (
              v_guid -- guid
            , NULL -- damage_id
            , -1 -- round_id
            , 3 -- player_id
            , 5 -- received_from_commander_player_id
            -- , -6 -- health_change
            , 0 -- life_gain
            , 6 -- life_loss
            , NULL -- commander_deaths
            , TRUE -- active
        )
    ;
*/
    CALL tcg.public.USP_TCG_MTG_Game_Round_Damage_Save (
		  a_comment := v_comment -- a_comment
		, a_guid := v_guid -- a_guid
		, a_user_id := v_user_id -- a_user_id
		, o_success := v_success -- o_success
	);
    RAISE NOTICE 'Success: %', CASE WHEN v_success THEN 'TRUE' ELSE 'FALSE' END;
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_MTG_Game_Round_Temp
;
SELECT *
-- DELETE
FROM tcg.public.TCG_MTG_Game_Round_Player_Damage_Temp
;
SELECT *
-- DELETE
FROM tcg.public.TCG_MTG_Game_Round TCG_ROUND
LEFT JOIN tcg.public.TCG_MTG_Game GAME ON TCG_ROUND.game_id = GAME.game_id
;
SELECT *
-- DELETE
FROM tcg.public.TCG_MTG_Game_Round_Player_Damage PLAYER_DAMAGE
LEFT JOIN tcg.public.TCG_MTG_Game_Round TCG_ROUND ON PLAYER_DAMAGE.round_id = TCG_ROUND.round_id
LEFT JOIN tcg.public.TCG_MTG_Game GAME ON TCG_ROUND.game_id = GAME.game_id
ORDER BY
	GAME.game_id DESC
	, TCG_ROUND.display_order
	, PLAYER_DAMAGE.player_id
	, PLAYER_DAMAGE.received_from_commander_player_id
;
SELECT *
FROM tcg.public.TCG_MTG_Game GAME
ORDER BY GAME.game_id DESC
;


	/*
	INSERT INTO tcg.public.TCG_MTG_Game_Round_Temp (
		  guid
	    , round_id
        , game_id
        , notes
        , display_order
        , active
	)
	VALUES (
          v_guid -- guid
        , -1 -- round_id
        , 4 -- game_id
        , 'Beaten' -- notes
        , 5 -- display_order
        , TRUE -- active
    )
    ;

	INSERT INTO tcg.public.TCG_MTG_Game_Round_Player_Damage_Temp (
		  guid
        , damage_id
        , round_id
        , player_id
        , received_from_commander_player_id
        -- , health_change
        , life_gain
        , life_loss
        , commander_deaths
        , active
	)
	VALUES
          (
              v_guid -- guid
            , NULL -- damage_id
            , -1 -- round_id
            , 3 -- player_id
            , NULL -- received_from_commander_player_id
            -- , -4 -- health_change
            , 0 -- life_gain
            , 4 -- life_loss
            , 1 -- commander_deaths
            , TRUE -- active
        )
		, (
              v_guid -- guid
            , NULL -- damage_id
            , -1 -- round_id
            , 3 -- player_id
            , 2 -- received_from_commander_player_id
            -- , -5 -- health_change
            , 0 -- life_gain
            , 5 -- life_loss
            , NULL -- commander_deaths
            , TRUE -- active
        )
		, (
              v_guid -- guid
            , NULL -- damage_id
            , -1 -- round_id
            , 3 -- player_id
            , 5 -- received_from_commander_player_id
            -- , -6 -- health_change
            , 0 -- life_gain
            , 6 -- life_loss
            , NULL -- commander_deaths
            , TRUE -- active
        )
    ;
	*/

SELECT 
FROM tcg.public.TCG_MTG_Game_Player PLAYER
WHERE PLAYER.game_id = 35


