-- backfill_dispatch_address.sql — remplit le champ `address` (adresse de service) des Dispatch Jobs
-- issus du pont legacy, qui ne l'écrivait jamais (175 jobs, address vide).
--   A) jobs AVEC service_location → adresse depuis la SL (address_line + ville, en ignorant 'N/A')
--   B) jobs SANS service_location → adresse extraite du sujet (partie après ' · ', l'ancien append du pont)
-- Le pont écrit désormais `address` directement (création + backfill update) ; ce script rattrape l'historique.
-- Idempotent (ne touche que address = '' / NULL). À lancer AVANT toute re-sync (qui nettoie le sujet).
\timing on
SELECT character_maximum_length AS address_maxlen FROM information_schema.columns
 WHERE table_name = 'tabDispatch Job' AND column_name = 'address';

BEGIN;
-- A) depuis la Service Location liée
WITH a AS (
  UPDATE "tabDispatch Job" dj
     SET address = left(NULLIF(trim(both ', ' FROM concat_ws(', ', NULLIF(sl.address_line,''), NULLIF(sl.city,'N/A'))), ''), 140),
         modified = NOW()
    FROM "tabService Location" sl
   WHERE dj.service_location = sl.name
     AND coalesce(dj.legacy_ticket_id,'') <> ''
     AND coalesce(dj.address,'') = ''
     AND NULLIF(trim(both ', ' FROM concat_ws(', ', NULLIF(sl.address_line,''), NULLIF(sl.city,'N/A'))), '') IS NOT NULL
  RETURNING 1
)
SELECT count(*) AS rempli_via_service_location FROM a;

-- B) depuis le sujet (jobs sans SL : le pont y avait collé l'adresse après ' · ')
WITH b AS (
  UPDATE "tabDispatch Job" dj
     SET address = left(trim(split_part(subject, ' · ', 2)), 140),
         modified = NOW()
   WHERE coalesce(dj.legacy_ticket_id,'') <> ''
     AND coalesce(dj.address,'') = ''
     AND position(' · ' IN subject) > 0
     AND length(trim(split_part(subject, ' · ', 2))) > 0
  RETURNING 1
)
SELECT count(*) AS rempli_via_sujet FROM b;
COMMIT;

-- État final
SELECT count(*) FILTER (WHERE coalesce(address,'') <> '') AS addr_ok,
       count(*) FILTER (WHERE coalesce(address,'') = '')  AS addr_vide,
       count(*) AS total
FROM "tabDispatch Job" WHERE coalesce(legacy_ticket_id,'') <> '';

-- Reste-t-il des jobs ACTIFS (open/assigned) sans adresse ? (à diagnostiquer le cas échéant)
SELECT name, status, left(subject,70) AS subject, service_location
FROM "tabDispatch Job"
WHERE coalesce(legacy_ticket_id,'') <> '' AND coalesce(address,'') = ''
  AND status IN ('open','assigned','in_progress')
ORDER BY modified DESC LIMIT 10;
