DO $$
DECLARE
	_path  character varying(256) := 'patch-2026_05_06-ProjectsUserAccessRights';
	_build integer := 16636;
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 RECURSIVE ValidAccess AS (
        SELECT
            uar."Id",
            uar."EntityId",
            uar."UserId",
            ARRAY[p."Id"] AS path
        FROM public."UserAccessRights" uar
        JOIN public."Projects" p
            ON p."Id" = uar."EntityId"
        WHERE uar."EntityType" = 38
          AND uar."UserId" > 0
          AND (
                p."ParentId" IS NULL
                OR NOT EXISTS (
                    SELECT 1
                    FROM public."Projects" parent
                    WHERE parent."Id" = p."ParentId"
                )
          )

        union all

        SELECT
            uar."Id",
            uar."EntityId",
            uar."UserId",
            va.path || p."Id"
        FROM ValidAccess va
        JOIN public."Projects" p
            ON p."ParentId" = va."EntityId"
        JOIN public."UserAccessRights" uar
            ON uar."EntityId" = p."Id"
           AND uar."UserId" = va."UserId"
           AND uar."EntityType" = 38
        WHERE uar."UserId" > 0
          AND NOT p."Id" = ANY(va.path)
          AND array_length(va.path, 1) < 100
    )

    UPDATE public."UserAccessRights" uar
    SET "UserId" = -uar."UserId"
    WHERE uar."EntityType" = 38
      AND uar."UserId" > 0
      AND NOT EXISTS (
            SELECT 1
            FROM ValidAccess va
            WHERE va."Id" = uar."Id"
      );
        


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