-- Find PF partners with same name words in different order
-- (e.g., "COLILIE DANIELA" vs "DANIELA COLILIE")
-- Run on prod to assess scope of firstname/lastname swap duplicates
--
-- 02.04.2026 - diagnostic script for PF name dedup fix
-- 06.04.2026 - adaugat adrese pentru verificare duplicate reale

SELECT a.id_part   AS id1,
       a.denumire  AS name1,
       a.dataora   AS dataora1,
       addr1.judet AS judet1,
       addr1.localitate AS localitate1,
       addr1.strada AS strada1,
       b.id_part   AS id2,
       b.denumire  AS name2,
       b.dataora   AS dataora2,
       addr2.judet AS judet2,
       addr2.localitate AS localitate2,
       addr2.strada AS strada2,
       CASE WHEN UPPER(TRIM(addr1.judet)) = UPPER(TRIM(addr2.judet))
                 AND UPPER(TRIM(addr1.localitate)) = UPPER(TRIM(addr2.localitate))
                 AND UPPER(TRIM(addr1.strada)) = UPPER(TRIM(addr2.strada))
            THEN 'DA - DUPLICAT REAL'
            WHEN UPPER(TRIM(addr1.judet)) = UPPER(TRIM(addr2.judet))
                 AND UPPER(TRIM(addr1.localitate)) = UPPER(TRIM(addr2.localitate))
            THEN 'POSIBIL - acelas judet+localitate'
            ELSE 'NU - adrese diferite'
       END AS duplicat_real
  FROM nom_parteneri a
  JOIN nom_parteneri b
    ON a.id_part < b.id_part
   AND NVL(a.sters, 0) = 0
   AND NVL(b.sters, 0) = 0
   AND a.tip_persoana = 2
   AND b.tip_persoana = 2
   AND INSTR(UPPER(TRIM(a.denumire)), ' ') > 0
   AND INSTR(UPPER(TRIM(a.denumire)), ' ', INSTR(UPPER(TRIM(a.denumire)), ' ') + 1) = 0
   AND UPPER(TRIM(b.denumire)) =
       TRIM(SUBSTR(UPPER(TRIM(a.denumire)), INSTR(UPPER(TRIM(a.denumire)), ' ') + 1))
       || ' ' ||
       TRIM(SUBSTR(UPPER(TRIM(a.denumire)), 1, INSTR(UPPER(TRIM(a.denumire)), ' ') - 1))
  LEFT JOIN (SELECT id_part, judet, localitate, strada,
                    ROW_NUMBER() OVER (PARTITION BY id_part ORDER BY principala DESC, id_adresa DESC) rn
               FROM vadrese_parteneri) addr1
    ON addr1.id_part = a.id_part AND addr1.rn = 1
  LEFT JOIN (SELECT id_part, judet, localitate, strada,
                    ROW_NUMBER() OVER (PARTITION BY id_part ORDER BY principala DESC, id_adresa DESC) rn
               FROM vadrese_parteneri) addr2
    ON addr2.id_part = b.id_part AND addr2.rn = 1
 WHERE EXTRACT(YEAR FROM a.dataora) = 2026 OR EXTRACT(YEAR FROM b.dataora) = 2026
 ORDER BY duplicat_real, a.id_part;
