create table if not exists sys_user_data_scope_user (
  id bigserial primary key,
  tenant_id bigint not null,
  viewer_user_id bigint not null,
  owner_user_id bigint not null,
  resource_type varchar(50) not null default 'ALL',
  enabled boolean not null default true,
  expire_at timestamptz,
  remark varchar(500),
  created_by bigint,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now(),
  is_deleted integer not null default 0
);

create unique index if not exists uk_user_data_scope_user
  on sys_user_data_scope_user (tenant_id, viewer_user_id, owner_user_id, resource_type)
  where is_deleted = 0;

create index if not exists idx_user_data_scope_viewer
  on sys_user_data_scope_user (tenant_id, viewer_user_id, resource_type, enabled);

create index if not exists idx_user_data_scope_owner
  on sys_user_data_scope_user (tenant_id, owner_user_id);

comment on table sys_user_data_scope_user is '用户到用户的数据可见范围授权';
comment on column sys_user_data_scope_user.viewer_user_id is '被授权查看数据的用户ID';
comment on column sys_user_data_scope_user.owner_user_id is '数据归属用户ID';
comment on column sys_user_data_scope_user.resource_type is '授权资源类型：OPPORTUNITY/EXPANSION/DAILY_REPORT/CHECKIN等';

do $$
declare
  v_system_parent_id bigint;
  v_menu_perm_id bigint;
  v_view_perm_id bigint;
  v_update_perm_id bigint;
  v_has_role_permission_tenant boolean;
begin
  perform setval('sys_permission_perm_id_seq', coalesce((select max(perm_id) from sys_permission), 0) + 1, false);
  perform setval('sys_role_permission_id_seq', coalesce((select max(id) from sys_role_permission), 0) + 1, false);

  select exists (
    select 1
    from information_schema.columns
    where table_schema = current_schema()
      and table_name = 'sys_role_permission'
      and column_name = 'tenant_id'
  ) into v_has_role_permission_tenant;

  select perm_id
    into v_system_parent_id
  from sys_permission
  where code = 'system'
    and coalesce(is_deleted, 0) = 0
  order by perm_id
  limit 1;

  if v_system_parent_id is null then
    insert into sys_permission (
      parent_id, name, code, perm_type, level, path, component, icon,
      sort_order, is_visible, status, description, meta, is_deleted, created_at, updated_at
    ) values (
      null, '系统管理', 'system', 'directory', 1, null, null, 'SettingOutlined',
      110, 1, 1, '系统管理目录', '{}'::jsonb, 0, now(), now()
    )
    returning perm_id into v_system_parent_id;
  end if;

  select perm_id
    into v_menu_perm_id
  from sys_permission
  where code = 'menu:data-scope-users'
  order by perm_id
  limit 1;

  if v_menu_perm_id is null then
    insert into sys_permission (
      parent_id, name, code, perm_type, level, path, component, icon,
      sort_order, is_visible, status, description, meta, is_deleted, created_at, updated_at
    ) values (
      v_system_parent_id, '数据授权管理', 'menu:data-scope-users', 'menu', 2,
      '/data-scope-users', null, 'TeamOutlined', 8, 1, 1,
      '配置用户可额外查看哪些人员名下的数据', jsonb_build_object('tenantScoped', true), 0, now(), now()
    )
    returning perm_id into v_menu_perm_id;
  else
    update sys_permission
    set parent_id = v_system_parent_id,
        name = '数据授权管理',
        perm_type = 'menu',
        level = 2,
        path = '/data-scope-users',
        component = null,
        icon = 'TeamOutlined',
        sort_order = 8,
        is_visible = 1,
        status = 1,
        description = '配置用户可额外查看哪些人员名下的数据',
        meta = jsonb_build_object('tenantScoped', true),
        is_deleted = 0,
        updated_at = now()
    where perm_id = v_menu_perm_id;
  end if;

  select perm_id
    into v_view_perm_id
  from sys_permission
  where code = 'user_data_scope:view'
  order by perm_id
  limit 1;

  if v_view_perm_id is null then
    insert into sys_permission (
      parent_id, name, code, perm_type, level, path, component, icon,
      sort_order, is_visible, status, description, meta, is_deleted, created_at, updated_at
    ) values (
      v_menu_perm_id, '查看数据授权', 'user_data_scope:view', 'button', 3,
      null, null, null, 1, 1, 1, '查看用户数据授权配置', '{}'::jsonb, 0, now(), now()
    )
    returning perm_id into v_view_perm_id;
  else
    update sys_permission
    set parent_id = v_menu_perm_id,
        name = '查看数据授权',
        perm_type = 'button',
        level = 3,
        sort_order = 1,
        is_visible = 1,
        status = 1,
        description = '查看用户数据授权配置',
        meta = '{}'::jsonb,
        is_deleted = 0,
        updated_at = now()
    where perm_id = v_view_perm_id;
  end if;

  select perm_id
    into v_update_perm_id
  from sys_permission
  where code = 'user_data_scope:update'
  order by perm_id
  limit 1;

  if v_update_perm_id is null then
    insert into sys_permission (
      parent_id, name, code, perm_type, level, path, component, icon,
      sort_order, is_visible, status, description, meta, is_deleted, created_at, updated_at
    ) values (
      v_menu_perm_id, '修改数据授权', 'user_data_scope:update', 'button', 3,
      null, null, null, 2, 1, 1, '保存用户数据授权配置', '{}'::jsonb, 0, now(), now()
    )
    returning perm_id into v_update_perm_id;
  else
    update sys_permission
    set parent_id = v_menu_perm_id,
        name = '修改数据授权',
        perm_type = 'button',
        level = 3,
        sort_order = 2,
        is_visible = 1,
        status = 1,
        description = '保存用户数据授权配置',
        meta = '{}'::jsonb,
        is_deleted = 0,
        updated_at = now()
    where perm_id = v_update_perm_id;
  end if;

  if v_has_role_permission_tenant then
    insert into sys_role_permission (role_id, perm_id, tenant_id, is_deleted, created_at, updated_at)
    select role_source.role_id, perm_source.perm_id, role_source.tenant_id, 0, now(), now()
    from (
      select distinct role_id, tenant_id
      from (
        select r.role_id, r.tenant_id
        from sys_role r
        where coalesce(r.is_deleted, 0) = 0
          and (
            r.role_code in ('TENANT_ADMIN', 'ADMIN', 'SYS_ADMIN', 'PLATFORM_ADMIN', 'SUPER_ADMIN')
            or r.role_name ilike '%管理员%'
            or r.role_name ilike '%admin%'
          )
        union
        select r.role_id, r.tenant_id
        from sys_user u
        join sys_user_role ur on ur.user_id = u.user_id and coalesce(ur.is_deleted, 0) = 0
        join sys_role r on r.role_id = ur.role_id and coalesce(r.is_deleted, 0) = 0
        where coalesce(u.is_deleted, 0) = 0
          and u.username = 'admin'
      ) granted_roles
    ) role_source
    cross join (
      select unnest(array[v_menu_perm_id, v_view_perm_id, v_update_perm_id]) as perm_id
    ) perm_source
    where perm_source.perm_id is not null
      and not exists (
        select 1
        from sys_role_permission rp
        where rp.role_id = role_source.role_id
          and rp.perm_id = perm_source.perm_id
      );

    update sys_role_permission rp
    set tenant_id = coalesce(rp.tenant_id, r.tenant_id),
        is_deleted = 0,
        updated_at = now()
    from sys_role r,
         sys_permission p
    where rp.role_id = r.role_id
      and p.perm_id = rp.perm_id
      and coalesce(r.is_deleted, 0) = 0
      and p.code in ('menu:data-scope-users', 'user_data_scope:view', 'user_data_scope:update')
      and (
        r.role_code in ('TENANT_ADMIN', 'ADMIN', 'SYS_ADMIN', 'PLATFORM_ADMIN', 'SUPER_ADMIN')
        or r.role_name ilike '%管理员%'
        or r.role_name ilike '%admin%'
        or exists (
          select 1
          from sys_user u
          join sys_user_role ur on ur.user_id = u.user_id and coalesce(ur.is_deleted, 0) = 0
          where coalesce(u.is_deleted, 0) = 0
            and u.username = 'admin'
            and ur.role_id = r.role_id
        )
      );
  else
    insert into sys_role_permission (role_id, perm_id, is_deleted, created_at, updated_at)
    select role_source.role_id, perm_source.perm_id, 0, now(), now()
    from (
      select distinct role_id
      from (
        select r.role_id
        from sys_role r
        where coalesce(r.is_deleted, 0) = 0
          and (
            r.role_code in ('TENANT_ADMIN', 'ADMIN', 'SYS_ADMIN', 'PLATFORM_ADMIN', 'SUPER_ADMIN')
            or r.role_name ilike '%管理员%'
            or r.role_name ilike '%admin%'
          )
        union
        select r.role_id
        from sys_user u
        join sys_user_role ur on ur.user_id = u.user_id and coalesce(ur.is_deleted, 0) = 0
        join sys_role r on r.role_id = ur.role_id and coalesce(r.is_deleted, 0) = 0
        where coalesce(u.is_deleted, 0) = 0
          and u.username = 'admin'
      ) granted_roles
    ) role_source
    cross join (
      select unnest(array[v_menu_perm_id, v_view_perm_id, v_update_perm_id]) as perm_id
    ) perm_source
    where perm_source.perm_id is not null
      and not exists (
        select 1
        from sys_role_permission rp
        where rp.role_id = role_source.role_id
          and rp.perm_id = perm_source.perm_id
      );

    update sys_role_permission rp
    set is_deleted = 0,
        updated_at = now()
    from sys_role r,
         sys_permission p
    where rp.role_id = r.role_id
      and p.perm_id = rp.perm_id
      and coalesce(r.is_deleted, 0) = 0
      and p.code in ('menu:data-scope-users', 'user_data_scope:view', 'user_data_scope:update')
      and (
        r.role_code in ('TENANT_ADMIN', 'ADMIN', 'SYS_ADMIN', 'PLATFORM_ADMIN', 'SUPER_ADMIN')
        or r.role_name ilike '%管理员%'
        or r.role_name ilike '%admin%'
        or exists (
          select 1
          from sys_user u
          join sys_user_role ur on ur.user_id = u.user_id and coalesce(ur.is_deleted, 0) = 0
          where coalesce(u.is_deleted, 0) = 0
            and u.username = 'admin'
            and ur.role_id = r.role_id
        )
      );
  end if;
end
$$;
