ALTER TABLE unit
ADD COLUMN hierarchy_path TEXT;


WITH RECURSIVE tree AS (
  -- Gốc: các đơn vị không có cha (NULL/blank) hoặc mã cha không tồn tại
  SELECT
      u.unit_id,
      u.code,
      u.belonged_unit_code,
      COALESCE(NULLIF(BTRIM(u.code), ''), u.code) AS label,
      COALESCE(NULLIF(BTRIM(u.code), ''), u.code) AS path,
      ARRAY[u.code]::text[] AS visited,
      1 AS lvl
  FROM unit u
  WHERE u.belonged_unit_code IS NULL
        OR BTRIM(u.belonged_unit_code) = ''
        OR NOT EXISTS (
              SELECT 1 FROM unit p WHERE p.code = u.belonged_unit_code
        )

  UNION ALL

  -- Nối con vào đường dẫn của cha, giới hạn tối đa 6 cấp, chặn vòng lặp
  SELECT
      c.unit_id,
      c.code,
      c.belonged_unit_code,
      COALESCE(NULLIF(BTRIM(c.code), ''), c.code) AS label,
      tree.path || '>' || COALESCE(NULLIF(BTRIM(c.code), ''), c.code) AS path,
      tree.visited || c.code AS visited,
      tree.lvl + 1 AS lvl
  FROM unit c
  JOIN tree ON tree.code = c.belonged_unit_code
  WHERE tree.lvl < 6
    AND NOT (c.code = ANY(tree.visited))   -- chống vòng lặp
)
UPDATE unit u
SET hierarchy_path = tree.path
FROM tree
WHERE u.unit_id = tree.unit_id;
