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

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

  if (!uid) {
    return reply.status(401).send('unauthorized');
  }

  if (method === 'POST') {
    if (!body?.name) {
      return reply.status(400).send('not enough body params: name');
    }

    if (!body?.map_key) {
      return reply.status(400).send('not enough body params: map_key');
    }

    const { rows = [] } = await dataInsert({
      pg,
      id: params.id,
      table: 'gis.maps',
      data: body,
      uid,
    });
    return reply.status(200).send(rows[0]);
  }

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

  const row = await dataUpdate({
    pg,
    id: params.id,
    table: 'gis.maps',
    data: body,
    uid,
  });
  return reply.status(200).send(row);
}
