import { getPG, getSelect } from "@opengis/fastify-table/utils.js";
const pg = getPG();

export default async function select(ids, options) {
  if (!ids || (Array.isArray(ids) && ids.length === 0) || ids === '') {
    return '';
  }

  const data = options.hash?.data;
  if (!data && data !== false && data !== 0) return '';
  try {
    const idsArray = Array.isArray(ids) ? ids : [ids];

    const classifier = await getSelect(data);



    if (!classifier) return `Не знайдено класифікатор ${data}`;

    const arr = classifier.arr || []
    if (classifier.sql && typeof classifier.sql === 'string') {



      const metaQuery = `SELECT * FROM (${classifier.sql})q LIMIT 0`;
      const meta = await pg.query(metaQuery);
      const idColumn = meta.fields[0].name;
      const textColumn = meta.fields[1].name;

      const q = `SELECT "${idColumn}" AS id, "${textColumn}" AS text FROM (${classifier.sql}) q WHERE "${idColumn}"::text = ANY($1::text[])`;
      const values = [idsArray.map(id => String(id))];

      const { rows } = await pg.query(q, values);
      Object.assign(arr, rows);

    }
    if (!arr.length) return idsArray;

    const results = idsArray.map(id => {
      const result = arr.find(el => String(el.id) == String(id));
      return result ? result.text : '';
    });

    return results.filter(Boolean).join(', ');
  } catch (err) {
    return `Сталася помилка.<!-- err: ${err.toString()} -->`;
  }
}
