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

async function updateTemplate(client, body, uid, id) {
    if (!body || !id) return;

    await dataDelete({
        pg: client,
        id,
        table: 'admin.templates',
        uid,
    });
    const rowCount = await dataInsert({
        pg: client,
        id,
        table: 'admin.templates',
        data: { body, name: id },
        uid,
    }).then(el => el.rowCount);
    return rowCount;
}
export default async function addService({
    method, params = {}, body, pg = pgClients.client, user = {},
}, reply) {
    if (method === 'PUT' && !params.id) {
        return reply.status(400).send('not enough params: id');
    }

    const { uid = '0' } = user;

    const client = await pg.connect();
    try {
        await client.query('begin');

        if (method === 'POST') {
            const { rows = [] } = await dataInsert({
                pg: client,
                id: params.id,
                table: 'gis.services',
                data: body,
                uid,
            });
            const istemplate = await updateTemplate(client, body.html, uid, rows[0]?.service_id);
            await client.query('commit');
            return reply.status(200).send(rows[0]);
        }


        const row = await dataUpdate({
            pg: client,
            id: params.id,
            table: 'gis.services',
            data: body,
            uid,
        });
        const istemplate = await updateTemplate(client, body.html, uid, params.id);
        await client.query('commit');
        return reply.status(200).send(row);

    } catch (err) {
        await client.query('rollback');
        return reply.status(500).send(err.toString());
    } finally {
        client.release();
    }
}