-- Rattache chaque serveur à une des 3 zones SANEF :
--   - DMZ  : déjà attribuée via le script update_zone_dmz.sql (depuis xlsx)
--   - EMV  : serveurs avec 'emv' dans le hostname (zone PCI-DSS)
--   - LAN  : tous les autres (par défaut)
-- Idempotent. Ne touche pas aux serveurs déjà en DMZ.

\echo '═══ AVANT ═══'

SELECT COALESCE(z.name, '∅ NULL') AS zone, COUNT(*) AS nb
  FROM public.servers s
  LEFT JOIN public.zones z ON s.zone_id = z.id
 GROUP BY z.name
 ORDER BY z.name NULLS FIRST;

\echo '═══ 1) Création zones LAN et EMV si absentes ═══'

INSERT INTO public.zones (name, description, is_dmz)
SELECT 'LAN', 'Zone LAN par défaut (Satellite vpdsiasat2)', false
 WHERE NOT EXISTS (SELECT 1 FROM public.zones WHERE LOWER(name) = 'lan');

INSERT INTO public.zones (name, description, is_dmz)
SELECT 'EMV', 'Zone EMV (PCI-DSS, hostname contient ''emv'')', false
 WHERE NOT EXISTS (SELECT 1 FROM public.zones WHERE LOWER(name) = 'emv');

\echo '═══ 2) Affectation EMV (hostname contient ''emv'', sauf DMZ) ═══'

UPDATE public.servers s
   SET zone_id = (SELECT id FROM public.zones WHERE LOWER(name) = 'emv' LIMIT 1),
       updated_at = NOW()
 WHERE LOWER(s.hostname::text) LIKE '%emv%'
   AND ( s.zone_id IS NULL
         OR s.zone_id NOT IN (SELECT id FROM public.zones
                               WHERE is_dmz = true OR LOWER(name) = 'dmz') );

\echo '═══ 3) Affectation LAN par défaut (zone_id NULL restants) ═══'

UPDATE public.servers
   SET zone_id = (SELECT id FROM public.zones WHERE LOWER(name) = 'lan' LIMIT 1),
       updated_at = NOW()
 WHERE zone_id IS NULL;

\echo '═══ APRÈS ═══'

SELECT COALESCE(z.name, '∅ NULL') AS zone, COUNT(*) AS nb
  FROM public.servers s
  LEFT JOIN public.zones z ON s.zone_id = z.id
 GROUP BY z.name
 ORDER BY z.name NULLS FIRST;

\echo '═══ Vérification : EMV doit contenir uniquement les hostnames *emv* ═══'

SELECT z.name AS zone, COUNT(*) AS nb,
       MIN(s.hostname::text) AS exemple_min,
       MAX(s.hostname::text) AS exemple_max
  FROM public.servers s
  JOIN public.zones z ON s.zone_id = z.id
 WHERE LOWER(z.name) = 'emv'
 GROUP BY z.name;
