-- Nettoyage FQDN incohérents avec la convention SANEF
--   v[r|t|d|v]* → doit être .sanef-rec.fr  (recette/test/dev/qualif)
--   v[p|l]*    → doit être .sanef.groupe ou .sanef.fr  (prod/legacy)
-- Les FQDN ne respectant pas la convention sont mis à NULL → _resolve()
-- recalculera dynamiquement via la cascade ordonnée des suffixes.
--
-- Exécutable plusieurs fois sans dommage. Avant/Après pour traçabilité.

\echo '═══ AVANT ═══'

SELECT 'recette_avec_fqdn_prod (à nettoyer)' AS scope, COUNT(*) AS nb
  FROM servers
 WHERE LOWER(SUBSTRING(hostname::text, 2, 1)) IN ('r','t','d','v')
   AND fqdn IS NOT NULL
   AND (fqdn ILIKE '%.sanef.groupe' OR fqdn ILIKE '%.sanef.fr')
UNION ALL
SELECT 'prod_avec_fqdn_recette (à nettoyer)' AS scope, COUNT(*) AS nb
  FROM servers
 WHERE LOWER(SUBSTRING(hostname::text, 2, 1)) IN ('p','l')
   AND fqdn IS NOT NULL
   AND fqdn ILIKE '%.sanef-rec.fr'
UNION ALL
SELECT 'fqdn_total_actuel' AS scope, COUNT(*) AS nb
  FROM servers WHERE fqdn IS NOT NULL AND fqdn != ''
UNION ALL
SELECT 'fqdn_null_actuel' AS scope, COUNT(*) AS nb
  FROM servers WHERE fqdn IS NULL OR fqdn = '';

\echo '═══ APERÇU 10 LIGNES INCOHÉRENTES ═══'

SELECT hostname, fqdn,
       CASE WHEN LOWER(SUBSTRING(hostname::text, 2, 1)) IN ('r','t','d','v')
            THEN 'recette_attendu_sanef-rec.fr'
            ELSE 'prod_attendu_sanef.groupe' END AS pourquoi
  FROM servers
 WHERE fqdn IS NOT NULL
   AND (
        (LOWER(SUBSTRING(hostname::text, 2, 1)) IN ('r','t','d','v')
            AND (fqdn ILIKE '%.sanef.groupe' OR fqdn ILIKE '%.sanef.fr'))
     OR (LOWER(SUBSTRING(hostname::text, 2, 1)) IN ('p','l')
            AND fqdn ILIKE '%.sanef-rec.fr')
       )
 ORDER BY hostname
 LIMIT 10;

\echo '═══ NETTOYAGE ═══'

-- Recette/test/dev/qualif : FQDN .sanef.groupe / .sanef.fr → NULL
UPDATE servers
   SET fqdn = NULL, updated_at = NOW()
 WHERE LOWER(SUBSTRING(hostname::text, 2, 1)) IN ('r','t','d','v')
   AND fqdn IS NOT NULL
   AND (fqdn ILIKE '%.sanef.groupe' OR fqdn ILIKE '%.sanef.fr');

-- Prod / legacy : FQDN .sanef-rec.fr → NULL
UPDATE servers
   SET fqdn = NULL, updated_at = NOW()
 WHERE LOWER(SUBSTRING(hostname::text, 2, 1)) IN ('p','l')
   AND fqdn IS NOT NULL
   AND fqdn ILIKE '%.sanef-rec.fr';

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

SELECT 'recette_avec_fqdn_prod (résiduel)' AS scope, COUNT(*) AS nb
  FROM servers
 WHERE LOWER(SUBSTRING(hostname::text, 2, 1)) IN ('r','t','d','v')
   AND fqdn IS NOT NULL
   AND (fqdn ILIKE '%.sanef.groupe' OR fqdn ILIKE '%.sanef.fr')
UNION ALL
SELECT 'prod_avec_fqdn_recette (résiduel)' AS scope, COUNT(*) AS nb
  FROM servers
 WHERE LOWER(SUBSTRING(hostname::text, 2, 1)) IN ('p','l')
   AND fqdn IS NOT NULL
   AND fqdn ILIKE '%.sanef-rec.fr'
UNION ALL
SELECT 'fqdn_total_apres' AS scope, COUNT(*) AS nb
  FROM servers WHERE fqdn IS NOT NULL AND fqdn != ''
UNION ALL
SELECT 'fqdn_null_apres' AS scope, COUNT(*) AS nb
  FROM servers WHERE fqdn IS NULL OR fqdn = '';
