--- data-users

-- Default roles
INSERT INTO user_roles (
  id,
  title,
  description,
  admin,
  deleted,
  permissions,
  created_at,
  updated_at)
  SELECT *
  FROM (VALUES
    (
      nextval('user_roles_id_seq'),
      'Administrator',
      'System administrator',
      TRUE,
      FALSE,
      '',
      now(),
      now()
    ),
    (
      nextval('user_roles_id_seq'),
      'User',
      'User',
      FALSE,
      FALSE,
      '',
      now(),
      now()
    )) AS t (
       id,
       title,
       description,
       admin,
       deleted,
       permissions,
       created_at,
       updated_at)
  WHERE (SELECT COUNT(*)
         FROM users) > 0;

-- Default user roles
UPDATE users
SET role_id = (
  SELECT id
  FROM user_roles
  WHERE title = 'User')
WHERE deleted = FALSE;

-- Admin user roles
UPDATE users
SET role_id = (
  SELECT id
  FROM user_roles
  WHERE title = 'Administrator')
WHERE exists(
    SELECT *
    FROM user_groups_members m
      JOIN user_groups g ON g.id = m.group_id
    WHERE
      g.admin = TRUE
      AND m.deleted = FALSE
      AND m.user_id = users.id);
