-- Rollback the best-effort Department seeding.
-- Non-destructive on the structural tables themselves (those came in 018).
-- We only undo the rows this migration inserted: every (department, user)
-- row whose Department name matches the user's free-text field, and then
-- Department rows with no other memberships. Users' free-text dezernat
-- column is untouched.

DELETE FROM paliad.department_members dm
 USING paliad.users u, paliad.departments d
 WHERE dm.user_id = u.id
   AND dm.department_id = d.id
   AND u.dezernat IS NOT NULL
   AND d.name = btrim(u.dezernat);

DELETE FROM paliad.departments d
 WHERE NOT EXISTS (
     SELECT 1 FROM paliad.department_members m
      WHERE m.department_id = d.id
 )
   AND d.lead_user_id IS NULL;
