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

CREATE TEMP TABLE w_dbsetup AS
    SELECT
        CASE WHEN oid = 0 THEN oid ELSE 1 END AS oid,
    	code,
    	texte
    FROM activite.t_type_hospi_pmsi
    ORDER BY code LIMIT 0
;

-- 2/3 : Peuplement de la table temporaire
INSERT INTO w_dbsetup(
    oid,
    code,
    texte
)
VALUES
(1, '11', 'MCO hospitalisés'),
(1, '12', 'MCO Ambulatoires'),
(1, '15', 'MCO Séances'),
(1, '21', 'SSR hospitalisation complète'),
(1, '22', 'SSR hospitalisation partiel'),
(1, '24', 'SSR Autres'),
(1, '30', 'Externes'),
(1, '31', 'PSY hospitalisation complète'),
(1, '32', 'PSY hospitalisation partiel'),
(1, '41', 'HAD')
;

-- 3/3 : Màj de la table iCTI
UPDATE w_dbsetup SET 
	oid =  w_dbsetup.code::bigint;

UPDATE activite.t_type_hospi_pmsi SET 
	oid =  w_dbsetup.oid,
	code = w_dbsetup.code,
	texte = w_dbsetup.texte
FROM w_dbsetup
WHERE w_dbsetup.oid = t_type_hospi_pmsi.oid AND w_dbsetup.oid = 0;

UPDATE activite.t_type_hospi_pmsi SET
	texte = w_dbsetup.texte
FROM w_dbsetup
WHERE 1=1
	AND activite.t_type_hospi_pmsi.code = w_dbsetup.code
	AND activite.t_type_hospi_pmsi.texte IS DISTINCT FROM w_dbsetup.texte
;

INSERT INTO activite.t_type_hospi_pmsi(oid,code,texte)
	SELECT oid, code, texte
	FROM w_dbsetup 
	WHERE 1=1 
		AND oid NOT IN (SELECT oid FROM activite.t_type_hospi_pmsi)
;