begin;

set search_path to public;

do $$
declare
  v_system_parent_id bigint;
  v_menu_perm_id bigint;
  v_view_perm_id bigint;
  v_execute_perm_id bigint;
  v_has_role_permission_tenant boolean;
begin
  -- Align sequences before any upsert-style inserts so the script stays rerunnable.
  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:owner-transfer'
  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:owner-transfer', 'menu', 2,
      '/owner-transfer', null, 'SwapOutlined', 7, 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 = '/owner-transfer',
        component = null,
        icon = 'SwapOutlined',
        sort_order = 7,
        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 = 'owner_transfer: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, '查看归属人转移', 'owner_transfer: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_execute_perm_id
  from sys_permission
  where code = 'owner_transfer:execute'
  order by perm_id
  limit 1;

  if v_execute_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, '执行归属人转移', 'owner_transfer:execute', 'button', 3,
      null, null, null, 2, 1, 1, '执行商机、拓展销售人员、拓展渠道归属人转移', '{}'::jsonb, 0, now(), now()
    )
    returning perm_id into v_execute_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_execute_perm_id;
  end if;

  -- Grant the menu to:
  -- 1. Built-in admin/platform roles
  -- 2. Any role currently held by username = 'admin' (fallback for custom role naming)
  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_execute_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:owner-transfer', 'owner_transfer:view', 'owner_transfer:execute')
      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_execute_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
    set is_deleted = 0,
        updated_at = now()
    where perm_id in (v_menu_perm_id, v_view_perm_id, v_execute_perm_id)
      and role_id in (
        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
      );
  end if;
end $$;

commit;
