-- Re-sync des colonnes text legacy s.environnement et s.domaine avec
-- les valeurs résolues via domain_env_id → domain_environments → domains/environments.
-- Corrige les serveurs où les colonnes text étaient désynchronisées par
-- des updates précédents qui ne touchaient que domain_env_id.
-- Idempotent.

\echo '═══ AVANT (lignes désynchronisées) ═══'

SELECT 'desync_env' AS scope, COUNT(*)
  FROM servers s
  JOIN domain_environments de ON s.domain_env_id = de.id
  JOIN environments e ON de.environment_id = e.id
 WHERE COALESCE(s.environnement,'') <> COALESCE(e.name,'')
UNION ALL
SELECT 'desync_dom' AS scope, COUNT(*)
  FROM servers s
  JOIN domain_environments de ON s.domain_env_id = de.id
  JOIN domains d ON de.domain_id = d.id
 WHERE COALESCE(s.domaine,'') <> COALESCE(d.name,'');

\echo '═══ RE-SYNC ═══'

UPDATE servers s
   SET environnement = e.name,
       domaine = d.name,
       updated_at = NOW()
  FROM domain_environments de
  JOIN environments e ON de.environment_id = e.id
  JOIN domains d ON de.domain_id = d.id
 WHERE s.domain_env_id = de.id
   AND ( COALESCE(s.environnement,'') <> COALESCE(e.name,'')
      OR COALESCE(s.domaine,'')        <> COALESCE(d.name,'') );

\echo '═══ APRÈS (résiduel doit être 0) ═══'

SELECT 'desync_env_residuel' AS scope, COUNT(*)
  FROM servers s
  JOIN domain_environments de ON s.domain_env_id = de.id
  JOIN environments e ON de.environment_id = e.id
 WHERE COALESCE(s.environnement,'') <> COALESCE(e.name,'')
UNION ALL
SELECT 'desync_dom_residuel' AS scope, COUNT(*)
  FROM servers s
  JOIN domain_environments de ON s.domain_env_id = de.id
  JOIN domains d ON de.domain_id = d.id
 WHERE COALESCE(s.domaine,'') <> COALESCE(d.name,'');
