CREATE OR REPLACE FUNCTION public.history_trigger_function()
    RETURNS TRIGGER AS
$$
DECLARE
    schema_name        TEXT;
    history_table_name TEXT;
BEGIN
    -- Construct the name of the history table based on the current table
    schema_name := TG_TABLE_SCHEMA;
    history_table_name := TG_TABLE_NAME || '_history';

    IF (TG_OP = 'INSERT') THEN
        RETURN NEW;
    END IF;

    -- Insert the old row into the history table on UPDATE or DELETE
    IF (TG_OP = 'UPDATE' OR TG_OP = 'DELETE') THEN
        EXECUTE format(
                'INSERT INTO %I.%I SELECT ($1).*',
                schema_name,
                history_table_name
                )
            USING OLD;
    END IF;

    -- For UPDATE, update the UpdatedUtc column and return the new row
    IF (TG_OP = 'UPDATE') THEN
        NEW.updated := NOW(); -- Update the UpdatedUtc column
        RETURN NEW;
    END IF;

    -- For DELETE, return OLD to allow the deletion
    IF (TG_OP = 'DELETE') THEN
        RETURN OLD;
    END IF;
END;
$$ LANGUAGE plpgsql;