
CREATE OR REPLACE FUNCTION tcg.public.FN_before_insert_Error()
RETURNS TRIGGER AS $$
DECLARE
    r_change_set RECORD;
BEGIN
    NEW.created_on = COALESCE(NEW.created_on, CURRENT_TIMESTAMP);
    NEW.updated_last_on = COALESCE(NEW.updated_last_on, CURRENT_TIMESTAMP);

    IF NEW.change_set_id IS NULL THEN
		RAISE EXCEPTION 'Change Set ID must be provided.';
    END IF;

    SELECT *
    INTO r_change_set
    FROM tcg.public.TCG_Change_Set CHANGE_SET
    WHERE NEW.change_set_id = CHANGE_SET.change_set_id
    ;

    IF FOUND THEN
        NEW.created_by_user_id := COALESCE(NEW.created_by_user_id, r_change_set.updated_last_by_user_id);
        NEW.updated_last_by_user_id := COALESCE(NEW.updated_last_by_user_id, r_change_set.updated_last_by_user_id);
        NEW.created_on := COALESCE(NEW.created_on, r_change_set.updated_last_on);
    ELSE
        RAISE EXCEPTION 'Change Set % not found.', NEW.change_set_id;
    END IF;

    RETURN NEW;
END;
$$ LANGUAGE plpgsql
;

CREATE OR REPLACE FUNCTION tcg.public.FN_before_update_Error()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_last_on = CURRENT_TIMESTAMP;

    IF OLD.change_set_id IS NOT DISTINCT FROM NEW.change_set_id THEN
		RAISE EXCEPTION 'New Change Set ID must be provided.';
    END IF;

    INSERT INTO tcg.public.Error_Audit (
		  error_id
        , message_field
        , value_prev
        , value_new
        , change_set_id
    )
	-- Changed guid
	SELECT NEW.error_id, 'guid', OLD.guid::TEXT, NEW.guid::TEXT, NEW.change_set_id
		WHERE OLD.guid IS NOT DISTINCT FROM NEW.guid
	UNION
	-- Changed error_type_id
	SELECT NEW.error_id, 'error_type_id', OLD.error_type_id::TEXT, NEW.error_type_id::TEXT, NEW.change_set_id
		WHERE OLD.error_type_id IS NOT DISTINCT FROM NEW.error_type_id
	UNION
	-- Changed message
	SELECT NEW.error_id, 'message', OLD.message, NEW.message, NEW.change_set_id
		WHERE OLD.message IS NOT DISTINCT FROM NEW.message
	UNION
	-- Changed display_order
	SELECT NEW.error_id, 'display_order', OLD.display_order::TEXT, NEW.display_order::TEXT, NEW.change_set_id
		WHERE OLD.display_order IS NOT DISTINCT FROM NEW.display_order
	UNION
	-- Changed active
	SELECT NEW.error_id, 'active', OLD.active::TEXT, NEW.active::TEXT, NEW.change_set_id
		WHERE OLD.active IS NOT DISTINCT FROM NEW.active
    ;
    
    RETURN NEW;
END;
$$ LANGUAGE plpgsql
;

CREATE TRIGGER TRI_before_insert_Error
    BEFORE INSERT ON tcg.public.Error
    FOR EACH ROW
    EXECUTE FUNCTION tcg.public.FN_before_insert_Error()
;
CREATE TRIGGER TRI_before_update_Error
    BEFORE UPDATE ON tcg.public.Error
    FOR EACH ROW
    EXECUTE FUNCTION tcg.public.FN_before_update_Error()
;