-- 1/3 : Création de la table temporaire
DROP TABLE IF EXISTS w_dbsetup
;

CREATE TEMP TABLE w_dbsetup AS
    SELECT
    t_chart.type,
    t_chart.category,
    t_chart.name,
    t_chart.default_time_calc,
    t_chart.label_view_code,
    t_chart.code,
    array_agg(DISTINCT t_indicateur_serie.code) as serie_code
		FROM pmsi.t_chart
		LEFT JOIN pmsi.t_indicateur_serie ON ARRAY[t_indicateur_serie.oid] <@ t_chart.serie_id
		GROUP BY 1,2,3,4,5,6
		ORDER BY 1 LIMIT 0
;

-- 2/3 : Peuplement de la table temporaire
INSERT INTO w_dbsetup(
    type,
    category,
    name,
    default_time_calc,
    label_view_code,
    code,
    serie_code
)
VALUES
('card', 'date', 'Carte', 'val', 0, 'CTI_INFO', '{"CTI_DMSHOSP", "CTI_GHM80", "CTI_NBSEJ", "CTI_NBSEJGR"}'),
('donut', 'CTI_GHM#C', 'Sejours PMSI par CAS', 'val', 0, 'CTI_NBSEJCAS', '{"CTI_NBSEJ"}'),
('spread', 'CTI_GHM#LS#CTI_GHMDA', 'CAT2A Moyen par Domaine Activite', 'val', 1, 'CTI_CAT2AMOYDA', '{"CTI_CAT2AAMBUMOY", "CTI_CAT2AHOSPMOY"}'),
('spread', 'CTI_GHM#LS#CTI_GHMDA', 'CAT2A par Domaine Activite', 'val', 1, 'CTI_CAT2ADA', '{"CTI_CAT2AAMBU", "CTI_CAT2AHOSP"}'),
('spread', 'CTI_GHM#LS#CTI_GHMDA', 'Nombre de sejours', 'val', 1, 'CTI_NBSEJ', '{"CTI_NBSEJFEMMES", "CTI_NBSEJHOMMES"}')
;

-- 3/3 : Màj de la table iCTI
TRUNCATE pmsi.t_chart;

INSERT INTO pmsi.t_chart(type, serie_id, category, name, default_time_calc, label_view_code, code)
	SELECT
		type,
		array_agg(DISTINCT t_indicateur_serie.oid),
		w_dbsetup.category,
		w_dbsetup.name,
		w_dbsetup.default_time_calc,
		w_dbsetup.label_view_code,
		w_dbsetup.code
	FROM w_dbsetup
	LEFT JOIN pmsi.t_indicateur_serie ON ARRAY[t_indicateur_serie.code] <@ w_dbsetup.serie_code
	GROUP BY 1,3,4,5,6,7
;