import { pgClients } from "@opengis/fastify-table/utils.js";

export default async function cartoBounds({ id, dataset }, pg = pgClients.client) {
    const sqlBounds = dataset.map(el => ({ tbl: el.table.split('.'), geom: el.gcol || 'geom' })).map(({ tbl, geom }) => `select ST_EstimatedExtent('${tbl[0]}','${tbl[1]}', '${geom}')`);

    const geom = await pg.query(
        `update gis.cartocss set             
        geom=(select st_extent(st_estimatedextent) from ( ${sqlBounds.join(' union all ')})q )
        where cartocss_id=$1 returning geom::box2d`,
        [id],
    ).then(e => e.rows?.[0]?.geom);

    const bounds = geom
        ? geom.replace(/[A-Z\)\(]+/g, '').split(/[ ,]+/).map(el => el - 0)
        : null;

    if (!bounds) {
        // throw new Error('empty bounds');
    }

    return bounds || [-180, -85.05112877980659, 180, 85.05112877980659];
}
