import { getToken } from '@opengis/fastify-table/utils.js';
/**
 * Автозаповнення колонок Реєстру
 *
 * @method put
 * @summary Автозаповнення колонок Реєстру
 * @alias gis.registers
 * @type api
 * @tag dataset
 * @param   {String} token - токен
 * @returns {Number} status - номер помилки
 * @returns {String} error - опис помилки
 * @returns {String} message - повідомлення про успішне виконання і передача певних даних
 */
export default async function insertColumns(req,reply) {
  const {pg, user, params} = req;
  const token = params.token;
  if (!token) return { message: 'empty token', status: 400 };
  try {

    const tokenData = await getToken({ token, uid: user?.uid });
    if (!tokenData) return reply.code(400).send({ message: 'access restricted', status: 400 });

    const { id, type } = JSON.parse(tokenData) || {};
    if (!id||!type) return reply.code(403).send({ message: 'access restricted', status: 403 });
    if (!['services','registers'].includes(type)) return reply.code(403).send({ message: 'invalid type', status: 403 });

    const tableColumn =  (type === 'registers') ? 'table_name':'source_path';
    const jsonColumn = (type === 'registers') ? 'columns':'attributes';
    const pk = (type === 'registers')?'register_id':'service_id';

    const select = `update gis.${type} set ${jsonColumn}=
        (select
        jsonb_agg(row_to_json(q)) as column_list
        from
        (select 
          q.column_name as name,
          case 
            when q.column_name='editor_id' and comment is null then 'Хто редагував'
            when q.column_name ilike '%geom%' and comment is null then 'Геометрія'
            when q.column_name='editor_date' and comment is null then 'Дата редагування'
            when q.column_name='image' and comment is null then 'Зображення'
            when q.column_name='file' and comment is null then 'Файл'
            when q.column_name='files' and comment is null then 'Файли'
            else comment
          end as ua, 
          case 
            when q.data_type in ('text','character varying') then 'text'
            when q.data_type ='ARRAY' then 'tags'
            when q.data_type in ('integer','numeric','double precision') then 'number'
            when q.data_type ='boolean' then 'yes/no'
            when q.data_type='USER-DEFINED' then 'geom'
            when q.data_type in ('date','timestamp without time zone') then 'date'
          end as format,
          '' as data,
          false as hidden_register,
          false as hidden_card
        from 
          (
            select 
              column_name, 
              data_type, 
              table_schema || '.' || table_name as table_name 
            from 
              (
                select 
                  distinct table_name, 
                  table_schema, 
                  column_name, 
                  data_type
                from 
                  information_schema.columns
              ) q
          ) q 
        
          left join lateral (
             SELECT
                pgd.description AS comment,
                 pgns.nspname||'.'||pgc.relname AS table_name,
                pg_attribute.attname AS column_name
                
                FROM
                pg_catalog.pg_description pgd
                JOIN pg_catalog.pg_class pgc ON pgd.objoid = pgc.oid
                JOIN pg_catalog.pg_namespace pgns ON pgc.relnamespace = pgns.oid
                JOIN pg_catalog.pg_attribute pg_attribute ON pgc.oid = pg_attribute.attrelid
                AND pg_attribute.attnum = pgd.objsubid
          )b on b.column_name=q.column_name and b.table_name=q.table_name
        where 
          q.table_name = (
            select 
              ${tableColumn} 
            from 
              gis.${type} 
            where
             ${pk} = '${id}'
          ) and q.column_name not in ('cdate','uid') and q.data_type<>'json')q
        )
        where ${pk} = '${id}'
        `;
    await pg.one(select);

    return { message: 'Колонки заповнені упішно', status: 200 };
  } catch (err) {
    return reply.code(500).send({ message: err.message, status: 500 });
  }
}
