-- Best-effort migration of the paliad.users.dezernat free-text field into
-- proper paliad.departments + paliad.department_members rows.
--
-- For every distinct non-empty users.dezernat value, create a Department in
-- the creator's primary office (first user we see with that name wins).
-- Every user whose free-text matches the Department name becomes a member.
-- The free-text column stays as-is (forward compatibility for users who
-- haven't been linked); a later cleanup can drop it once all rows have
-- a proper department_members row.

INSERT INTO paliad.departments (id, name, lead_user_id, office, created_at, updated_at)
SELECT gen_random_uuid(),
       btrim(u.dezernat),
       NULL,
       MIN(u.office),
       now(),
       now()
  FROM paliad.users u
 WHERE u.dezernat IS NOT NULL
   AND btrim(u.dezernat) <> ''
 GROUP BY btrim(u.dezernat)
ON CONFLICT DO NOTHING;

INSERT INTO paliad.department_members (department_id, user_id, created_at)
SELECT d.id, u.id, now()
  FROM paliad.users u
  JOIN paliad.departments d
    ON d.name = btrim(u.dezernat)
 WHERE u.dezernat IS NOT NULL
   AND btrim(u.dezernat) <> ''
ON CONFLICT DO NOTHING;
