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

import mapnik from '../../../plugins/mapnik/funcs/mapnik.js';
import cartoBounds from '../../mapnik/functions/cartoBounds.js';

const { RenderTile } = mapnik();

const { prefix = '/api' } = config;

const exclude = ['created_at', 'updated_at', 'created_by', 'updated_by'];

export default async function checkCarto({
    pg = pgClients.client, params,
}, reply) {
    const time = Date.now();
    if (!config.mapServerAddress) {
        return reply.status(400).send({ error: 'mapnik server address needed', code: 400 });
    }

    // extract all columns, migrations-agnostic
    const cartocss = await pg.query('select *, ARRAY[ST_XMin(geom), ST_YMin(geom),  ST_XMax(geom),  ST_YMax(geom)] as bounds, st_asgeojson(geom)::json as geom, source_path from gis.cartocss where cartocss_id=$1', [params.id]).then(el => el.rows?.[0]);

    if (!cartocss) {
        return reply.status(404).send({ error: `cartocss not found: ${params.id}`, code: 404 });
    }

    // filter system columns
    Object.keys(cartocss).filter(key => exclude.includes(key)).forEach(key => delete cartocss[key]);

    const rtile = await RenderTile({
        name: cartocss.source_path ? `vector/${cartocss.source_path}` : params.id, // required for cartocss
        width: 256,
        bbox: [3713463.7081504324, 6088362.176970857, 3713616.5822070027, 6088515.051027427],
        ttl: '0',
        // debug: query.debug,
    }).catch(err => ({ err: err.toString() }));

    // skip empty bounds[null,null,null,null]
    const bounds = cartocss.bounds && cartocss.geom ? cartocss.bounds : await cartoBounds({ id: params.id, dataset: cartocss.config, table: cartocss.card_table }, pg);

    return {
        time: Date.now() - time,
        ...cartocss,
        info: !!(cartocss.card_auto || (cartocss.card_html && cartocss.card_table)),
        url: `${prefix}/gis-rtile/${params.id}/{z}/{x}/{y}.png`,
        bounds,
        render: !!rtile.base64,
        renderError: rtile.err && config.local ? rtile.err : !!rtile.err,
    };
}
