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

import checkRasterFile from '../../../plugins/mapnik/funcs/checkRasterFile.js';

// todo: add to kamianske, remove custom api and test
// addHook('beforeCreateXmlMulti', ({ list = [], id }) => {
//     list.push({
//         id: 'mbd_existent_detail_id',
//         table: 'data_mbd.mbd_existent_detail',
//         relpath: 'upfile',
//         q: `select mbd_existent_detail_id, upfile
//         from data_mbd.mbd_existent_detail a
//         left join data_mbd.mbd b on a.mbd_id=b.mbd_id
//         where   material_type_id = '3245363247443870877'
//         and     upfile is not null
//         and     upfile ~ '.tif'
//         and     left(upfile,7) != '/files/'
//         ${id ? ` and mbd_existent_detail_id = '${id}'` : ''}`,
//     });
// });

export default async function createXmlMulti({
    pg = pgClients.client, params, query,
}, reply) {
    if (!config.mapServerAddress) {
        return reply.code(400).send({
            error: 'mapnik grpc service address not set',
            code: 400,
        });
    }

    if (config.ready?.mapnik !== true) {
        return reply.code(400).send({
            error: 'mapnik grpc service not ready',
            code: 400,
        });
    }

    const list = [{
        id: 'raster_id',
        relpath: 'source_path',
        table: 'gis.rasters',
        query: `source_path is not null ${params.id ? ` and raster_id = '${params.id}'` : ''}`,
    }];

    applyHookSync('beforeCreateXmlMulti', { list, id: params.id });

    const rows = await Promise.all(list.filter(el => el.id && el.table && el.relpath).map(async el => pg.query(el.q ? `select ${el.id} as id, ${el.relpath} as relpath, '${el.table}' as table from (${el.q})q` : `select ${el.id} as id, ${el.relpath} as relpath, '${el.table}' as table from ${el.table} where ${el.query || 'true'}`).then(e => e.rows || []))).then(e => e.flat());

    if (!rows.length) {
        return reply.status(404).send({ error: 'empty rows', code: 404 });
    }

    const results = await checkRasterFile({ arr: rows.map(row => row.relpath), reply, nocache: query.nocache });

    const q = Object.keys(results || {}).filter(key => results[key] && results[key].extent).map(key => {
        const { extent } = results[key];
        const extentString = `ST_MakeEnvelope(${extent[0]}, ${extent[1]}, ${extent[2]}, ${extent[3]}, 4326)`;

        const { id, table } = rows.find(row => row.relpath === key) || {};
        const pk = pg.pk?.[table];
        return id && pk ? `update ${table} set geom=${extentString} where ${pk}='${id}'` : null;
    })
        .filter(Boolean);

    if (config.trace) {
        console.log('createXmlMulti: update bounds of', q.length, 'rows');
    }

    if (q.length) await pg.query(q.join(';\n'));

    return reply.status(200).send('all finished');
}
