export default async function getPermissions({ pg, uid }) {
  if (!uid) return { all_layers: false, group_list: [] };
  const selectPermissions = `
            select
            case when a.user_type='admin' then true else a.all_layers end as all_layers,
            b.layer_list,
            c.group_list
            from admin.users a
            left join lateral (
                select array_agg(service_id) as layer_list
                from gis.services_users_rel
                where user_id = a.uid
            ) b on true
            left join lateral (
                select
                array_agg(distinct group_id) as group_list
                from
                (
                    select 
                    group_id
                    from gis.services
                    where is_active
                    and service_id = any(b.layer_list)

                    union all

                    select
                    group_id
                    from gis.ogc_service
                    where enabled and 
                    ogc_service_id = any(b.layer_list)

                    union all

                    select group_id
                    from gis.rasters
                    where is_active and 
                    raster_id = any(b.layer_list)

                    union all

                    select group_id
                    from gis.cartocss
                    where enabled and 
                    cartocss_id = any(b.layer_list)
                )q
                where group_id in (
                    select group_id
                    from gis.group_list
                    where enabled
                ) 
            ) c on true
            where a.uid = $1
            limit 1
        `;
  const { all_layers, group_list, layer_list } = await pg.query(selectPermissions, [uid]).then(el => el?.rows?.[0] || {});

  return { all_layers, group_list, layer_list };
}
