/* next-for role for levels */
CREATE TEMPORARY SEQUENCE global_level_order_serial;
CREATE TEMPORARY TABLE indoor_level_order AS
(
    WITH sorted_levels AS (
        SELECT
            ft.p_ft_id AS plan_id,
            ft.ft_id AS level_id,
            CAST (ft_attr.value AS bigint) AS level_order
        FROM ft, ft_attr
        WHERE ft.ft_type_id IN (2302, 2303) AND ft_attr.key = 'order' AND ft.ft_id = ft_attr.ft_id
        ORDER BY ft.p_ft_id, CAST (ft_attr.value AS bigint)
    )
    SELECT
        plan_id,
        level_id,
        level_order,
        NEXTVAL('global_level_order_serial') global_level_order
    FROM sorted_levels
);

/* selects rows from "indoor_level_order" table sequentially,
   and inserts rows column into ft_ft, ordered by 'global_level_order' */
INSERT INTO ft_ft
SELECT
    prev.level_id AS master_ft_id,
    curr.level_id AS slave_ft_id,
    'next-for' AS role
FROM indoor_level_order curr, indoor_level_order prev
WHERE curr.plan_id = prev.plan_id AND curr.global_level_order = prev.global_level_order + 1;

/* default-for role for plan and level */
INSERT INTO ft_ft
SELECT
    ft.p_ft_id AS master_ft_id,
    ft_attr.ft_id AS slave_ft_id,
    'default-for' AS role
FROM ft, ft_attr
WHERE ft.ft_type_id IN (2302, 2303) AND ft_attr.key = 'default' AND ft.ft_id = ft_attr.ft_id;

DROP SEQUENCE global_level_order_serial;
DROP TABLE indoor_level_order;
