
CREATE OR REPLACE FUNCTION tcg.public.FN_before_insert_TCG_Condition()
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_Condition()
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_Condition_Audit (
		  condition_id
        , name_field
        , value_prev
        , value_new
        , change_set_id
    )
	-- Changed name
	SELECT NEW.condition_id, 'name', OLD.name, NEW.name, NEW.change_set_id
		WHERE OLD.name IS NOT DISTINCT FROM NEW.name
	UNION
	-- Changed code
	SELECT NEW.condition_id, 'code', OLD.code, NEW.code, NEW.change_set_id
		WHERE OLD.code IS NOT DISTINCT FROM NEW.code
	UNION
	-- Changed description
	SELECT NEW.condition_id, 'description', OLD.description, NEW.description, NEW.change_set_id
		WHERE OLD.description IS NOT DISTINCT FROM NEW.description
	UNION
	-- Changed summary
	SELECT NEW.condition_id, 'summary', OLD.summary, NEW.summary, NEW.change_set_id
		WHERE OLD.summary IS NOT DISTINCT FROM NEW.summary
	UNION
	-- Changed us_name
	SELECT NEW.condition_id, 'us_name', OLD.us_name, NEW.us_name, NEW.change_set_id
		WHERE OLD.us_name IS NOT DISTINCT FROM NEW.us_name
	UNION
	-- Changed price_ratio_min
	SELECT NEW.condition_id, 'price_ratio_min', CAST(OLD.price_ratio_min AS VARCHAR), CAST(NEW.price_ratio_min AS VARCHAR), NEW.change_set_id
		WHERE OLD.price_ratio_min IS NOT DISTINCT FROM NEW.price_ratio_min
	UNION
	-- Changed price_ratio_max
	SELECT NEW.condition_id, 'price_ratio_max', CAST(OLD.price_ratio_max AS VARCHAR), CAST(NEW.price_ratio_max AS VARCHAR), NEW.change_set_id
		WHERE OLD.price_ratio_max IS NOT DISTINCT FROM NEW.price_ratio_max
	UNION
	-- Changed active
	SELECT NEW.condition_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_Condition
    BEFORE INSERT ON tcg.public.TCG_Condition
    FOR EACH ROW
    EXECUTE FUNCTION tcg.public.FN_before_insert_TCG_Condition()
;
CREATE TRIGGER TRI_before_update_TCG_Condition
    BEFORE UPDATE ON tcg.public.TCG_Condition
    FOR EACH ROW
    EXECUTE FUNCTION tcg.public.FN_before_update_TCG_Condition()
;