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

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

CREATE OR REPLACE FUNCTION tcg.public.FN_before_update_TCG_User()
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.TCG_User_Audit (
		  user_id
        , name_field
        , value_prev
        , value_new
        , change_set_id
    )
	-- Changed user_auth0_id
	SELECT NEW.user_id, 'user_auth0_id', OLD.user_auth0_id, NEW.user_auth0_id, NEW.change_set_id
		WHERE OLD.user_auth0_id IS NOT DISTINCT FROM NEW.user_auth0_id
	UNION
	-- Changed firstname
	SELECT NEW.user_id, 'firstname', OLD.firstname, NEW.firstname, NEW.change_set_id
		WHERE OLD.firstname IS NOT DISTINCT FROM NEW.firstname
	UNION
	-- Changed surname
	SELECT NEW.user_id, 'surname', OLD.surname, NEW.surname, NEW.change_set_id
		WHERE OLD.surname IS NOT DISTINCT FROM NEW.surname
	UNION
	-- Changed email
	SELECT NEW.user_id, 'email', OLD.email, NEW.email, NEW.change_set_id
		WHERE OLD.email IS NOT DISTINCT FROM NEW.email
	UNION
	-- Changed is_email_verified
	SELECT NEW.user_id, 'is_email_verified', OLD.is_email_verified::TEXT, NEW.is_email_verified::TEXT, NEW.change_set_id
		WHERE OLD.is_email_verified IS NOT DISTINCT FROM NEW.is_email_verified
	UNION
	-- Changed is_super_user
	SELECT NEW.user_id, 'is_super_user', OLD.is_super_user::TEXT, NEW.is_super_user::TEXT, NEW.change_set_id
		WHERE OLD.is_super_user IS NOT DISTINCT FROM NEW.is_super_user
	UNION
	-- Changed active
	SELECT NEW.user_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_TCG_User
    BEFORE INSERT ON tcg.public.TCG_User
    FOR EACH ROW
    EXECUTE FUNCTION tcg.public.FN_before_insert_TCG_User()
;
CREATE TRIGGER TRI_before_update_TCG_User
    BEFORE UPDATE ON tcg.public.TCG_User
    FOR EACH ROW
    EXECUTE FUNCTION tcg.public.FN_before_update_TCG_User()
;