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

export default async function addGisRegistry({
    method, params = {}, body, pg = pgClients.client, user = {},
}, reply) {
    if (method === 'POST') {

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

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

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

    const id = await pg.query('select register_id from gis.registers where register_key=$1', [params.slug]).then(el => el.rows?.[0]?.register_id) || params.slug;

    const row = await dataUpdate({
        pg,
        id,
        table: 'gis.registers',
        data: body,
        uid: user?.uid,
    });

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