import { pgClients } from '@opengis/fastify-table/utils.js';
import { attachClassifiers } from '../../../gis/registers/funcs/classifiers.js';
const pg = pgClients.client;

export default async function getInfo({ finalInfo, format }, reply) {
  if (!finalInfo) return { error: 'No data found' };

  const table = finalInfo?.table_name;
  const queryCondition = finalInfo?.query || '1=1';
  const columns = finalInfo?.columns || finalInfo?.attributes || '[]';
  const exportable = columns.filter(c => c.is_export);
  const selectNames = exportable.map(c => `"${c.name}"`);
  const selectSQL = `
    SELECT ${selectNames?.length ? selectNames.join(', ') : ''} ${format === 'geojson' || format === 'shp' ? `${selectNames?.length ? ',' : ''} ST_AsGeoJSON(geom)::json as geom` : ``}
    FROM ${table}
    WHERE ${queryCondition} ${format === 'geojson' || format === 'shp' ? `and geom is not null` : ``}
  `;

  if (format === 'shp') {
    const { rows: geomTypeRows } = await pg.query(`
      SELECT DISTINCT ST_GeometryType(geom) AS geom_type
      FROM ${table}
      WHERE geom IS NOT NULL
    `);
    const geometryTypes = geomTypeRows.map(row => row.geom_type);

    const sqlList = geometryTypes.map(type => {
      return {
        type,
        query: `
          SELECT ${selectNames.join(', ')} ${selectNames?.length ? ',' : ''}  ST_AsGeoJSON(geom)::json as geom
          FROM ${table}
          WHERE ${queryCondition} AND ST_GeometryType(geom) = '${type}' AND geom IS NOT NULL
        `,
      };
    });

    const { rows: [{ srid }] } = await pg.query(`
      SELECT ST_SRID(geom) AS srid
      FROM ${table}
      WHERE geom IS NOT NULL
      LIMIT 1;
    `);

    return {
      columns: exportable,
      table,
      srid: srid || 4326,
      geomTypes: geometryTypes,
      sqlList
    };
  }

  const { rows } = await pg.query(selectSQL);
  if (!rows?.length) {
    return reply.status(404).send({ message: 'Немає даних, які можна експортувати', status: 404 });
  }

  const classifiers = exportable
    .filter(col => col.data && ["select", "badge", "tags"].includes(col.format))
    .map(col => ({ name: col.name, classifier: col.data }));

  const rowsWithClassifiers = await attachClassifiers(rows, classifiers);

  const simplifiedRows = rowsWithClassifiers.map(row => {
    const newRow = { ...row };

    for (const key of Object.keys(newRow)) {
      if (key.endsWith('_data') && typeof newRow[key]?.text === 'string') {
        const baseKey = key.replace(/_data$/, '');
        newRow[baseKey] = newRow[key].text;
      }

      if (key.endsWith('_text') && typeof newRow[key] === 'string') {
        const baseKey = key.replace(/_text$/, '');
        newRow[baseKey] = newRow[key];
      }
    }

    return newRow;
  });

  return {
    rows: simplifiedRows,
    data: rows,
    columns: exportable,
    table
  };
}
