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

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

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

  const { id } = params;
  if (!id) return reply.status(400).send({ message: 'id is empty', status: 400 });

  const { config: dataset, style } = body;
  if (!dataset && !style) return reply.status(400).send({ message: 'config, style is empty', status: 400 });

  const selectCartocss = `select cartocss_id from gis.cartocss where cartocss_id=$1`;
  const cartocss = await pg.one(selectCartocss, [id]);
  if (!cartocss) return reply.status(404).send({ message: 'cartocss not found', status: 404 });

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

  await uploadXML({ id, dataset, style }, pg);

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