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

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

const { GetRasterInfo } = mapnik();

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

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

    const raster = pg.pk?.['gis.rasters']
        ? await pg.query('select raster_id, source_path from gis.rasters where raster_id=$1::text', [params.id])
            .then(el => el.rows?.[0] || {})
        : {};

    if (raster.raster_id && !raster.source_path) {
        return reply.status(400).send({ error: 'empty source_path', code: 400 });
    }

    if (!raster.raster_id) {
        const decodedPath = Buffer.from(params.id, 'base64url').toString('utf-8');
        Object.assign(raster, { source_path: decodedPath });
    }

    const data = await GetRasterInfo({
        path: raster.source_path,
        ttl: query.nocache ? '0' : '1h',
    });

    return { ...data, url: `${prefix}/gis-rtile/${Buffer.from(raster.source_path).toString('base64url')}/{z}/{x}/{y}.png` };
}
