-- Migration : ajoute servers.satellite_url avec backfill auto
--   - DMZ (zone "DMZ" ou domaine "DMZ") → vpdsiasat1.sanef.groupe
--   - Tous les autres                   → vpdsiasat2.sanef.groupe
-- Champ optionnel (override de la convention par défaut côté code).
-- Idempotent.

ALTER TABLE public.servers
    ADD COLUMN IF NOT EXISTS satellite_url text;

-- Backfill DMZ (par zone = 'DMZ' ou nom de domaine contenant 'DMZ')
UPDATE public.servers s
   SET satellite_url = 'vpdsiasat1.sanef.groupe',
       updated_at = NOW()
  FROM public.zones z, public.domain_environments de, public.domains d
 WHERE s.zone_id = z.id
   AND s.domain_env_id = de.id
   AND de.domain_id = d.id
   AND s.satellite_url IS NULL
   AND (z.is_dmz = true
        OR UPPER(z.name) = 'DMZ'
        OR UPPER(d.name) LIKE '%DMZ%'
        OR UPPER(d.code) = 'DMZ');

-- Backfill tout le reste (LAN par défaut)
UPDATE public.servers
   SET satellite_url = 'vpdsiasat2.sanef.groupe',
       updated_at = NOW()
 WHERE satellite_url IS NULL;

-- Compteurs après backfill
SELECT 'satellite_lan (vpdsiasat2)' AS scope, COUNT(*) AS nb
  FROM public.servers WHERE satellite_url = 'vpdsiasat2.sanef.groupe'
UNION ALL
SELECT 'satellite_dmz (vpdsiasat1)' AS scope, COUNT(*) AS nb
  FROM public.servers WHERE satellite_url = 'vpdsiasat1.sanef.groupe'
UNION ALL
SELECT 'satellite_null'              AS scope, COUNT(*) AS nb
  FROM public.servers WHERE satellite_url IS NULL;
