-- Clarify admin IA permissions for organization, user membership, and operations.

insert into staff_roles (code, name, description, default_entry, status, permissions, role_family, role_level, sort_order, is_system)
values (
  'system_admin',
  '系统运维管理员',
  '负责系统健康、配置检查、运维任务和操作审计。',
  '/admin/system',
  'active',
  array[
    'operations:read',
    'operations:write',
    'config_check:read',
    'ops_job:read',
    'ops_job:run',
    'audit:read',
    'org:read',
    'staff:read',
    'role:read'
  ]::text[],
  '系统管理',
  20,
  30,
  true
)
on conflict (code) do update set
  name = excluded.name,
  description = excluded.description,
  default_entry = excluded.default_entry,
  permissions = (
    select array_agg(distinct permission order by permission)
    from unnest(coalesce(staff_roles.permissions, '{}'::text[]) || excluded.permissions) as permission
  ),
  role_family = excluded.role_family,
  role_level = excluded.role_level,
  sort_order = excluded.sort_order,
  is_system = true,
  updated_at = now();

update staff_roles
set permissions = (
  select array_agg(distinct permission order by permission)
  from unnest(coalesce(permissions, '{}'::text[]) || array[
    'user:read',
    'membership_subscription:read',
    'membership_entitlement:read',
    'passport:read',
    'operations:read',
    'config_check:read',
    'ops_job:read'
  ]::text[]) as permission
)
where code in ('super_admin', 'operations_admin');

update staff_roles
set permissions = (
  select array_agg(distinct permission order by permission)
  from unnest(coalesce(permissions, '{}'::text[]) || array[
    'operations:read',
    'operations:write',
    'config_check:read',
    'ops_job:read',
    'ops_job:run',
    'audit:read'
  ]::text[]) as permission
)
where code = 'system_admin';

