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

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

const { RenderTile } = mapnik();

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

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

    const cartocss = await pg.query('select config, geom::box2d 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 });
    }

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

    const bounds = cartocss.geom || await cartoBounds({ id: params.id, dataset: cartocss.config }, pg);

    return {
        url: `${prefix}/gis-rtile/${params.id}/{z}/{x}/{y}.png`,
        bounds,
        render: !!rtile.base64,
        renderError: !!rtile.err,
    };
}
