DO $$
DECLARE
	_path  character varying(256) := 'patch-2026_03_13-FlexibleTables-IntToString.sql';
	_build integer := 16212;
BEGIN
	IF EXISTS (SELECT 1 FROM public."Versions" WHERE "Path" = _path) THEN
		RETURN;
	END IF;

	IF EXISTS (SELECT 1 FROM public."Versions" WHERE "Build" >= _build) THEN
		RETURN;
	END IF;

	BEGIN

		WITH moved_rows AS (
		DELETE FROM public."FlexibleFieldInt" fi
		USING public."FlexibleTableFields" f
		WHERE f."Id" = fi."FieldId" 
		  AND f."Type" = 1
		RETURNING fi."FieldId", fi."EntityId", fi."Value", fi."Timestamp", f."TableId"
		)
		INSERT INTO public."FlexibleFieldString" ("TableId", "FieldId", "EntityId", "Value", "Timestamp")
		SELECT "TableId", "FieldId", "EntityId", "Value"::text, "Timestamp"
		FROM moved_rows;

		WITH moved_rows AS (
			DELETE FROM public."FlexibleFieldBigInt" fbi
			USING public."FlexibleTableFields" f
			WHERE f."Id" = fbi."FieldId" 
			  AND f."Type" = 1
			RETURNING fbi."FieldId", fbi."EntityId", fbi."Value", fbi."Timestamp", f."TableId"
		)
		INSERT INTO public."FlexibleFieldString" ("TableId", "FieldId", "EntityId", "Value", "Timestamp")
		SELECT "TableId", "FieldId", "EntityId", "Value"::text, "Timestamp"
		FROM moved_rows;


		INSERT INTO public."Versions" ("Path", "Build") VALUES (_path, 0);

	EXCEPTION
		WHEN OTHERS THEN
			RAISE NOTICE '[ERR] %: %', _path, SQLERRM;
	END;
END;
$$;
