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

CREATE TEMP TABLE w_dbsetup AS
    SELECT 
    	t_type_article_cti.oid, 
    	t_type_article_cti.code, 
    	t_type_article_cti.texte
    FROM eco.t_type_article_cti
    ORDER BY code LIMIT 0
;

-- 2/3 : Peuplement de la table temporaire
INSERT INTO w_dbsetup(
    oid,
    code,
    texte
)
VALUES
(0, '*', 'Non renseigné'),
(1, 'DM', 'Dispositifs Médicaux'),
(1, 'DMI', 'Dispositifs Médicaux Implantables'),
(1, 'ECO', 'Economat'),
(1, 'MED', 'Médicaments'),
(1, 'ZZZ', 'Autres')
;

-- 3/3 : Màj de la table iCTI
-- Mise à jour des données
UPDATE eco.t_type_article_cti SET 
	code = w_dbsetup.code
FROM w_dbsetup
WHERE 
	t_type_article_cti.oid = w_dbsetup.oid 
	AND w_dbsetup.oid = 0;

UPDATE eco.t_type_article_cti SET 
	texte = w_dbsetup.texte
FROM w_dbsetup
WHERE 
	t_type_article_cti.code = w_dbsetup.code
	AND (
		t_type_article_cti.texte IS DISTINCT FROM w_dbsetup.texte
	);


INSERT INTO eco.t_type_article_cti(
	oid, 
	code, 
	texte)
SELECT 
	oid, 
	code,
	texte
FROM w_dbsetup 
WHERE 
	oid = 0 
	AND oid NOT IN (SELECT oid FROM eco.t_type_article_cti);


INSERT INTO eco.t_type_article_cti(
	code, 
	texte)
SELECT 
	w_dbsetup.code,
	w_dbsetup.texte
FROM w_dbsetup
WHERE 
	w_dbsetup.oid <> 0 
	AND w_dbsetup.code NOT IN (SELECT code FROM eco.t_type_article_cti WHERE code IS NOT NULL);