import { dataInsert, dataUpdate, pgClients } from "@opengis/fastify-table/utils.js";
export default async function addWidget({
    method, params = {}, body, pg = pgClients.client, user = {},
}, reply) {
    const { uid } = user;

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

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

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

    if (method === 'POST') {
        Object.assign(body, { map_id: params.map });
        const { rows = [] } = await dataInsert({
            pg,
            id: params.id,
            table: 'gis.widgets',
            data: body,
            uid,
        });
        return reply.status(200).send(rows[0]);
    }

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