-- Remplit les fqdn manquants à partir de hostname + domain_ltd.
-- Cible : servers où fqdn IS NULL/vide ET domain_ltd renseigné.
-- Idempotent.

\echo '═══ AVANT ═══'

SELECT 'fqdn_null'                AS scope, COUNT(*) FROM public.servers WHERE fqdn IS NULL OR fqdn = ''
UNION ALL
SELECT 'fqdn_null_avec_dltd'      AS scope, COUNT(*) FROM public.servers
 WHERE (fqdn IS NULL OR fqdn = '') AND domain_ltd IS NOT NULL AND domain_ltd <> ''
UNION ALL
SELECT 'fqdn_null_sans_dltd'      AS scope, COUNT(*) FROM public.servers
 WHERE (fqdn IS NULL OR fqdn = '') AND (domain_ltd IS NULL OR domain_ltd = '')
UNION ALL
SELECT 'fqdn_total'               AS scope, COUNT(*) FROM public.servers WHERE fqdn IS NOT NULL AND fqdn <> '';

\echo '═══ APERÇU 10 LIGNES À MAJ ═══'

SELECT hostname,
       domain_ltd,
       LOWER(hostname::text) || '.' || REGEXP_REPLACE(domain_ltd, '^\.+', '') AS fqdn_calcule
  FROM public.servers
 WHERE (fqdn IS NULL OR fqdn = '')
   AND domain_ltd IS NOT NULL AND domain_ltd <> ''
 ORDER BY hostname
 LIMIT 10;

\echo '═══ UPDATE ═══'

UPDATE public.servers
   SET fqdn = LOWER(hostname::text) || '.' || REGEXP_REPLACE(domain_ltd, '^\.+', ''),
       updated_at = NOW()
 WHERE (fqdn IS NULL OR fqdn = '')
   AND domain_ltd IS NOT NULL AND domain_ltd <> '';

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

SELECT 'fqdn_null'                AS scope, COUNT(*) FROM public.servers WHERE fqdn IS NULL OR fqdn = ''
UNION ALL
SELECT 'fqdn_null_avec_dltd_residuel' AS scope, COUNT(*) FROM public.servers
 WHERE (fqdn IS NULL OR fqdn = '') AND domain_ltd IS NOT NULL AND domain_ltd <> ''
UNION ALL
SELECT 'fqdn_null_sans_dltd'      AS scope, COUNT(*) FROM public.servers
 WHERE (fqdn IS NULL OR fqdn = '') AND (domain_ltd IS NULL OR domain_ltd = '')
UNION ALL
SELECT 'fqdn_total'               AS scope, COUNT(*) FROM public.servers WHERE fqdn IS NOT NULL AND fqdn <> '';
