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

export default async function cartoBounds({ id, dataset, table }, pg = pgClients.client) {
    if (!dataset?.length && !table) {
        return [-180, -85.05112877980659, 180, 85.05112877980659];
    }

    const sqlBounds = dataset
        ? dataset.map(el => ({ tbl: el.table.replace(/"/g, "").split('.'), geom: el.gcol || 'geom' })).map(({ tbl, geom }) => `select ST_Transform(ST_SetSRID( ST_EstimatedExtent('${tbl[0]}','${tbl[1]}', '${geom}'), (SELECT st_srid(${geom}) from ${tbl.join('.')} limit 1)),4326)`)
        : [`select ST_Transform(ST_SetSRID(ST_EstimatedExtent('${table.split('.')[0]}', '${table.split('.')[1]}', 'geom'),(SELECT st_srid(geom) from ${table} limit 1)),4326)`];

    const geom = await pg.query(
        `update gis.cartocss set             
        geom=(select st_extent(st_transform) 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];
}
