import path from 'node:path';

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

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

const { GetRasterStatus, CreateXML } = mapnik();

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

    const { id } = params;

    if (!id) {
        return reply.status(400).send({ error: 'not enough params: id', code: 400 });
    }

    const data = pg.pk?.['gis.rasters']
        ? await pg.query('select raster_id as id, source_path, srid, raster_zoom from gis.rasters where raster_id=$1::text', [id])
            .then(el => el.rows?.[0])
        : null;

    if (!data?.id) {
        return reply.status(404).send({ error: 'raster not found', code: 404 });
    }

    if (!data.source_path) {
        return reply.status(400).send({ error: 'raster source_path not set', code: 400 });
    }

    const relpath = `/map/raster/${data.source_path}`;

    // check raster upload status, skip for directories
    const uploadStatus = path.extname(relpath) ? await GetRasterStatus({ path: data.source_path }) : {};

    if (uploadStatus.exists === false) {
        return reply.status(400).send({ error: 'raster not uploaded', code: 400 });
    }

    if (uploadStatus.finished === false) {
        return reply.status(400).send({ error: 'upload not finished', code: 400 });
    }

    const callback = eventStream(reply);

    // create at xml/:id with name only, always - by path
    const resp = await CreateXML({
        path: data.source_path,
        name: id, // create additional xml named as primary key at xml directory
        previewZoom: data.raster_zoom, // preview<=>detailed, default = 16 if file size > 1GB
        srid: data.srid, // auto detected if not supplied
        vrt: query.vrt, // force vrt even if relpath leads to single raster file
        debug: query.debug, // stream debug info
        nocache: query.nocache, // recreate if exists
    }, callback);

    callback('finish', 1);
    return reply.status(200).send(resp);
}
