
CREATE OR REPLACE FUNCTION tcg.public.FN_before_insert_TCG_MTG_Deck()
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_MTG_Deck()
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_MTG_Deck_Audit (
		  deck_id
        , name_field
        , value_prev
        , value_new
        , change_set_id
    )
	-- Changed name
	SELECT NEW.deck_id, 'name', CAST(OLD.name AS VARCHAR), CAST(NEW.name AS VARCHAR), NEW.change_set_id
		WHERE OLD.name IS NOT DISTINCT FROM NEW.name
	UNION
	-- Changed is_commander
	SELECT NEW.deck_id, 'is_commander', OLD.is_commander::TEXT, NEW.is_commander::TEXT, NEW.change_set_id
		WHERE OLD.is_commander IS NOT DISTINCT FROM NEW.is_commander
	UNION
	-- Changed commander_bracket_id
	SELECT NEW.deck_id, 'commander_bracket_id', CAST(OLD.commander_bracket_id AS VARCHAR), CAST(NEW.commander_bracket_id AS VARCHAR), NEW.change_set_id
		WHERE OLD.commander_bracket_id IS NOT DISTINCT FROM NEW.commander_bracket_id
	UNION
	-- Changed active
	SELECT NEW.deck_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_MTG_Deck
    BEFORE INSERT ON tcg.public.TCG_MTG_Deck
    FOR EACH ROW
    EXECUTE FUNCTION tcg.public.FN_before_insert_TCG_MTG_Deck()
;
CREATE TRIGGER TRI_before_update_TCG_MTG_Deck
    BEFORE UPDATE ON tcg.public.TCG_MTG_Deck
    FOR EACH ROW
    EXECUTE FUNCTION tcg.public.FN_before_update_TCG_MTG_Deck()
;