-- fix error if function exists and return type not text i.e bigint

do $$

declare
m record;
_pk text;
_tables json;
_returnType text;

begin

select format_type(p.prorettype, null) as return_type
from pg_proc p
where p.proname = 'next_id'
and p.pronamespace = 'public'::regnamespace into _returnType;

if (_returnType != 'text') then
	raise notice 'default reassign start: % -> text', _returnType;

	CREATE EXTENSION if not exists "uuid-ossp";

	SELECT json_object_agg(a.attrelid::regclass, a.attname)
	FROM   pg_catalog.pg_attribute    a
	LEFT   JOIN pg_catalog.pg_attrdef d ON (a.attrelid, a.attnum) = (d.adrelid, d.adnum)
	WHERE  NOT a.attisdropped           -- no dropped (dead) columns
	AND    a.attnum   > 0               -- no system columns
	AND pg_get_expr(d.adbin, d.adrelid) = 'next_id()' into _tables;

	FOR m in (select json_object_keys(_tables) as table) loop
		_pk = _tables->>m.table;
		raise notice 'drop default: %,%', m.table, _pk;
		EXECUTE('alter table '|| m.table || ' alter column ' || _pk || ' set default null;');
	end loop;

	DROP FUNCTION IF EXISTS next_id();

	/* CREATE EXTENSION if not exists "uuid-ossp";
	ALTER EXTENSION "uuid-ossp" SET SCHEMA public; */

	CREATE OR REPLACE FUNCTION next_id()
	  RETURNS text AS
	$BODY$
	DECLARE

	BEGIN
	    -- return replace(public.uuid_generate_v4()::text, '-', '');
		-- return replace(gen_random_uuid()::text, '-', ''); -- native from postgres 13 onward
		return encode(public.gen_random_bytes(6), 'hex');
	END;
	$BODY$
	  LANGUAGE plpgsql VOLATILE
	  COST 100;

	FOR m in (select json_object_keys(_tables) as table) loop
		_pk = _tables->>m.table;
		raise notice 'reassign default: %, %', m.table, _pk;
		EXECUTE('alter table '|| m.table || ' alter column ' || _pk || ' set default next_id();');
	end loop;

	raise notice 'reassign default finish: %', _tables;
	
else 
	raise notice 'skip default reassign';

		/* CREATE EXTENSION if not exists "uuid-ossp";
		ALTER EXTENSION "uuid-ossp" SET SCHEMA public; */

	CREATE OR REPLACE FUNCTION next_id()
	  RETURNS text AS
	$BODY$
	DECLARE

	BEGIN
	    -- return replace(public.uuid_generate_v4()::text, '-', '');
		-- return replace(gen_random_uuid()::text, '-', ''); -- native from postgres 13 onward
		return encode(public.gen_random_bytes(6), 'hex');
	END;
	$BODY$
	  LANGUAGE plpgsql VOLATILE
	  COST 100;
end if;

end $$
