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

CREATE TEMP TABLE w_dbsetup AS
    SELECT 
    	oid as keepoid,
    	code,
    	texte
    FROM activite.t_traitement_epmsi
    ORDER BY code LIMIT 0
;

-- 2/3 : Peuplement de la table temporaire
INSERT INTO w_dbsetup(
    keepoid,
    code,
    texte
)
VALUES
(0, '**', 'Non renseigné'),
(41, 'EXHAD', 'PMSI HAD Transmis'),
(11, 'EXMCO', 'PMSI MCO Transmis'),
(31, 'EXPSY', 'PMSI PSY Transmis'),
(21, 'EXSSR', 'PMSI SSR Transmis'),
(5, 'HPMSI', 'HORS PMSI'),
(40, 'NEXHAD', 'PMSI HAD Non Transmis'),
(10, 'NEXMCO', 'PMSI MCO Non Transmis'),
(30, 'NEXPSY', 'PMSI PSY Non Transmis'),
(20, 'NEXSSR', 'PMSI SSR Non Transmis')
;

-- 3/3 : Màj de la table iCTI
UPDATE activite.t_traitement_epmsi SET 
	code = w_dbsetup.code,
	texte = w_dbsetup.texte
FROM w_dbsetup
WHERE w_dbsetup.keepoid = t_traitement_epmsi.oid AND w_dbsetup.keepoid = 0;

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

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

INSERT INTO activite.t_traitement_epmsi(oid,code,texte)
	SELECT keepoid, code, texte
	FROM w_dbsetup 
	WHERE 1=1
		AND keepoid <> 0 
		AND code NOT IN (SELECT code FROM activite.t_traitement_epmsi)
;