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

export default async function editMetadata(req, reply) {
  const { pg = pgClients.client, body, params } = req;
  const { type, id } = params || {};
  const { uid } = req.user || {};

  const q = {
    raster: 'select 1 from gis.rasters where raster_id = $1',
    css: 'select 1 from gis.cartocss where cartocss_id = $1',
    dataset: 'select 1 from gis.dataset where dataset_id = $1',
    service: 'select 1 from gis.services where service_id = $1',
  }[type];

  if (!q) {
    return reply.code(400).send({ error: 'invalid params: type', code: 400 });
  }

  const exists = await pg.query(q, [id]).then(el => el.rowCount || 0);

  if (!exists) {
    return reply.code(404).send({ error: `${type} not found: ${id}`, code: 404 });
  }

  const data = await dataUpsert({
    pg,
    id,
    table: 'gis.metadata',
    data: { ...body, type, layer_id: id },
    uid,
  });

  return reply.status(200).send(data);
}
