/* Collect closures geometry from rd_el's*/
CREATE TEMPORARY TABLE closure AS
(
    WITH raw_closure_line AS
    (
        SELECT
            ft.ft_id,
            ST_LineMerge(ST_Collect(rd_el.shape)) AS shape
        FROM ft
        JOIN ft_rd_el USING (ft_id)
        JOIN rd_el USING (rd_el_id)
        WHERE ft_type_id=2021/*urban-roadnet-closure*/
        GROUP BY 1
    )
    SELECT
        ft_id,
        rd_jc_id,
        rd_jc.shape AS rd_jc_shape,
        CASE WHEN ST_LineLocatePoint(raw_closure_line.shape, rd_jc.shape) > 0.5
            THEN ST_Reverse(raw_closure_line.shape)
            ELSE raw_closure_line.shape
        END AS shape
    FROM ft_rd_jc
    JOIN raw_closure_line USING(ft_id)
    JOIN rd_jc USING(rd_jc_id)
);

CREATE TEMPORARY TABLE closure_isocode AS
(
    SELECT DISTINCT closure.ft_id, ft_isocode.isocode
    FROM closure
    JOIN ft_isocode USING (ft_id)
);

INSERT INTO ft_edge (ft_id, edge_id)
(
    SELECT ft_id, ft_id AS edge_id
    FROM closure
);

INSERT INTO node (node_id, shape)
(
    SELECT DISTINCT
        rd_jc_id AS node_id,
        rd_jc_shape AS shape
    FROM closure
);

INSERT INTO node (node_id, shape)
(
    SELECT
        ft_id AS node_id,
        ST_EndPoint(shape) AS shape
    FROM closure
);

INSERT INTO edge (edge_id, f_node_id, t_node_id, shape)
(
    SELECT
        ft_id AS edge_id,
        rd_jc_id AS f_node_id,
        ft_id AS t_node_id,
        shape
    FROM closure
);

INSERT INTO edge_isocode (edge_id, isocode)
(
    SELECT ft_id, isocode FROM closure_isocode
);

INSERT INTO node_isocode (node_id, isocode)
(
    SELECT ft_id, isocode FROM closure_isocode
);

INSERT INTO node_isocode (node_id, isocode)
(
    SELECT DISTINCT rd_jc_id, isocode FROM closure_isocode
    JOIN closure USING (ft_id)
);

DELETE FROM ft_rd_el
USING closure
WHERE ft_rd_el.ft_id = closure.ft_id;

DELETE FROM ft_rd_jc
USING closure
WHERE ft_rd_jc.ft_id = closure.ft_id;

DROP TABLE closure;
DROP TABLE closure_isocode;
