import { metaFormat, pgClients, getTemplate } from '@opengis/fastify-table/utils.js';

export default async function getServicesCol({ params = {}, pg = pgClients.client }, reply) {
  const row = await getTemplate('layer', params.id) || await pg.query(`
           SELECT 
               service_id, source_path, attributes
           FROM gis.services where ${params.id ? 'service_id=$1' : '1=1'}
       `, [params.id].filter(Boolean)).then(el => el.rows[0] || {});

  if (!row.source_path) {
    return reply.status(404).send({ code: 404, message: 'source not found' });
  }

  const fields = await pg.query(` SELECT *  FROM ${row.source_path} limit 0`).then(el => el.fields);
  const field = fields.find(el => el.name === params.col);

  if (!field) {
    return reply.status(404).send({ message: { error: 'column not found', fields }, code: 404 });
  }

  const rows = await pg.query(`SELECT ${params.col}::text as id, ${params.col}, count(*) FROM ${row.source_path} 
        where ${params.col} is not null group by ${params.col} order by count(*) desc limit 10`).then(el => el.rows || []);

  const cls = row.attributes?.filter?.((col) => col.name && col.data && ['select', 'badge', 'tags'].includes(col.format)).reduce((acc, curr) => ({ ...acc, [curr.name]: curr.data }), {}) || {};

  await metaFormat({ rows, table: row.source_path, cls });

  const rows1 = rows.map(row => ({
    ...row[`${params.col}_data`], ...row, [`${params.col}_data`]: undefined, [params.col]: undefined,
  }));

  return reply.status(200).send({ rows: rows1, field, fields });
}
