-- Migration : suppression des colonnes legacy de servers (consolidées avec les nouvelles)
--   - snapshot_required → requires_snapshot
--   - pre_patch_script  → pre_patch_cmd
--   - post_patch_script → post_patch_cmd
--   - satellite_host    → satellite_url
--   - need_pct          → pct_required
-- ⚠ responsable_nom/email et referent_nom/email sont CONSERVÉS (le backfill
--   vers responsable_domaine_contact_id / referent_technique_contact_id
--   nécessite un fuzzy match qui sera fait dans un script séparé).
-- Idempotent.

\echo '═══ 1. Migration des données legacy → nouvelles ═══'

-- snapshot_required → requires_snapshot (si nouveau pas encore défini)
UPDATE public.servers
   SET requires_snapshot = snapshot_required, updated_at = NOW()
 WHERE requires_snapshot IS NULL
   AND snapshot_required IS NOT NULL;

-- pre_patch_script → pre_patch_cmd
UPDATE public.servers
   SET pre_patch_cmd = pre_patch_script, updated_at = NOW()
 WHERE pre_patch_cmd IS NULL
   AND pre_patch_script IS NOT NULL AND pre_patch_script != '';

-- post_patch_script → post_patch_cmd
UPDATE public.servers
   SET post_patch_cmd = post_patch_script, updated_at = NOW()
 WHERE post_patch_cmd IS NULL
   AND post_patch_script IS NOT NULL AND post_patch_script != '';

-- satellite_host → satellite_url (si vide)
UPDATE public.servers
   SET satellite_url = satellite_host, updated_at = NOW()
 WHERE (satellite_url IS NULL OR satellite_url = '')
   AND satellite_host IS NOT NULL AND satellite_host != '';

-- need_pct → pct_required (si nouveau false / NULL et legacy true)
UPDATE public.servers
   SET pct_required = need_pct, updated_at = NOW()
 WHERE need_pct = true
   AND (pct_required IS NULL OR pct_required = false);

\echo '═══ 2. Drop des views qui dépendent ═══'

DROP VIEW IF EXISTS public.v_patchable;
DROP VIEW IF EXISTS public.v_servers;
DROP VIEW IF EXISTS public.v_conformity_todo;

\echo '═══ 3. Drop des colonnes legacy ═══'

ALTER TABLE public.servers
    DROP COLUMN IF EXISTS snapshot_required,
    DROP COLUMN IF EXISTS pre_patch_script,
    DROP COLUMN IF EXISTS post_patch_script,
    DROP COLUMN IF EXISTS satellite_host,
    DROP COLUMN IF EXISTS need_pct;

\echo '═══ 4. Recréation des views avec les nouveaux noms ═══'

CREATE OR REPLACE VIEW public.v_servers AS
 SELECT s.id,
    s.hostname,
    s.fqdn,
    s.domain_ltd,
    d.name AS domaine,
    d.code AS domaine_code,
    e.name AS environnement,
    e.code AS env_code,
    z.name AS zone_reseau,
    s.os_family,
    s.os_version,
    s.machine_type,
    s.tier,
    s.etat,
    s.licence_support,
    s.is_bdd,
    s.is_flux_libre,
    s.is_emv,
    s.is_podman,
    s.pct_required,
    s.patch_os_owner,
    COALESCE(s.patch_excludes, de.patch_excludes, d.default_excludes) AS effective_excludes,
    s.responsable_nom,
    s.referent_nom,
    s.ssh_method,
    s.ssh_user,
    s.mode_operatoire,
    s.commentaire,
    s.satellite_url,
    s.requires_snapshot,
    s.snap_can_be_skipped,
    s.cluster_id,
    s.cluster_order
   FROM public.servers s
   LEFT JOIN public.domain_environments de ON s.domain_env_id = de.id
   LEFT JOIN public.domains d ON de.domain_id = d.id
   LEFT JOIN public.environments e ON de.environment_id = e.id
   LEFT JOIN public.zones z ON s.zone_id = z.id;

CREATE OR REPLACE VIEW public.v_patchable AS
 SELECT id, hostname, fqdn, domain_ltd, domaine, domaine_code, environnement,
        env_code, zone_reseau, os_family, os_version, machine_type, tier, etat,
        licence_support, is_bdd, is_flux_libre, is_emv, is_podman, pct_required,
        patch_os_owner, effective_excludes, responsable_nom, referent_nom,
        ssh_method, ssh_user, mode_operatoire, commentaire, satellite_url,
        requires_snapshot, snap_can_be_skipped, cluster_id, cluster_order
   FROM public.v_servers
  WHERE patch_os_owner::text = 'secops'
    AND etat::text = 'en_production'
    AND licence_support::text IN ('active', 'els');

CREATE OR REPLACE VIEW public.v_conformity_todo AS
 SELECT s.hostname,
        d.name AS domaine,
        e.name AS environnement,
        s.tier,
        s.patch_os_owner,
        (s.responsable_nom IS NULL) AS resp_missing
   FROM public.servers s
   LEFT JOIN public.domain_environments de ON s.domain_env_id = de.id
   LEFT JOIN public.domains d ON de.domain_id = d.id
   LEFT JOIN public.environments e ON de.environment_id = e.id
  WHERE s.etat::text = 'en_production'
    AND (s.patch_os_owner::text = 'a_definir' OR s.responsable_nom IS NULL);

\echo '═══ 5. Vérification ═══'

SELECT column_name, data_type
  FROM information_schema.columns
 WHERE table_name = 'servers'
   AND column_name IN ('snapshot_required','pre_patch_script','post_patch_script',
                       'satellite_host','need_pct')
 ORDER BY column_name;
-- Résultat attendu : 0 ligne (toutes les legacy ont été drop)
