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

import uploadXML from '../../mapnik/functions/uploadXML.js';

export default async function addCartocss(req, reply) {
  const {
    pg = pgClients.client, body, params, user,
  } = req;

  const cartocss = await pg.query('select cartocss_id, source_path, config, style 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', code: 404 });
  }

  const sourcePath = body.source_path || cartocss.source_path;

  const config = body.config || cartocss.config;
  const style = body.style || cartocss.style;

  const data = { ...body, config };

  await dataUpdate({
    pg,
    id: params.id,
    table: 'gis.cartocss',
    data,
    uid: user?.uid,
  });

  // if not from static xml file
  if (!data.source_path) {
    await uploadXML({
      id: params.id,
      dataset: config,
      style,
      source_path: sourcePath,
    }, pg);
  }

  return reply.status(200).send({ message: 'cartocss updated', code: 200 });
}
