import getPermissions from './utils/get.permissions.js';

export default async function gisCatalog(req, reply) {
  const { pg, user } = req;

  if (!user?.uid) return reply.status(403).send({ status: 403, message: 'access restricted' });

  // permissions
  const { all_layers, group_list, layer_list } = await getPermissions({ pg, uid: user.uid });
  if (!all_layers && !group_list?.length && !layer_list?.length) {
    return reply.status(200).send({
      status: 204, categoriesCount: 0, layersCount: 0, servicesCount: 0, rastersCount: 0, categories: [], layers: [],
    });
  }

  // groups
  const selectCategories = `select group_id as category_id, trim(group_name) as name, icon from gis.group_list where enabled and ${all_layers ? '$1' : 'group_id = any($1)'} order by trim(group_name)`;
  const { rows: categories } = await pg.query(selectCategories, [all_layers ? true : group_list]);
  const categoriesCount = categories?.length || 0;

  // services
  const selectLayers = `
    select
    service_id as layer_id,
    group_id as category_id,
    name,
    service_type,
    source_path,
    geom_type /*,
   style,
    popup,
    card,
    bi,
    legend,
    attributes,
    popup*/
    from gis.services
    where is_active and 
    ${all_layers ? '$1' : 'service_id = any($1)'}`;
  const { rows: services } = await pg.query(selectLayers, [all_layers ? true : layer_list]);
  const servicesCount = services?.length || 0;

  // ogc services
  const selectOgcServices = `select ogc_service_id as layer_id,group_id as category_id,name,service as service_type,url,html from gis.ogc_service where enabled and ${all_layers ? '$1' : 'ogc_service_id = any($1)'}`;
  const { rows: ogcServices } = await pg.query(selectOgcServices, [all_layers ? true : layer_list]);
  const ogcServicesCount = ogcServices?.length || 0;

  // rasters
  const selectRasters = `select raster_id as layer_id, group_id as category_id,name,'raster' as service_type,source_path from gis.rasters where enabled and ${all_layers ? '$1' : 'raster_id = any($1)'}`;
  const { rows: rasters } = await pg.query(selectRasters, [all_layers ? true : layer_list]);
  const rastersCount = rasters?.length || 0;

  // cartocss
  const selectCartocss = `select cartocss_id as layer_id, group_id as category_id,name,'cartocss' as service_type,config from gis.cartocss where enabled and ${all_layers ? '$1' : 'cartocss_id = any($1)'}`;
  const { rows: cartocss } = await pg.query(selectCartocss, [all_layers ? true : layer_list]);
  const cartocssCount = cartocss?.length || 0;

  const layers = [
    ...services,
    ...ogcServices,
    ...rasters,
    ...cartocss,
  ];
  const layersCount = layers?.length || 0;

  const res = {
    categoriesCount,
    layersCount,
    servicesCount,
    ogcServicesCount,
    rastersCount,
    cartocssCount,
    categories,
    layers,

  };
  const statusCode = (!layersCount && !categoriesCount) ? 204 : 200;

  return reply.status(statusCode).send(res);
}
