export default async function catalogPermissionsEdit(req, reply) {
    const { pg, params, body } = req;
    const { uid } = params;
    if (!uid) return reply.status(403).send({ status: 403, message: 'access restricted' });
    if (!body?.length) return reply.status(400).send({ status: 400, message: 'body is empty' });

    try {
        await pg.one(`delete from gis.services_users_rel where user_id = $1`, [uid]);

        const sql = [];
        body.map(el => {
            const insertSql = `('${el?.service_id}','${uid}','${uid}',${(el?.actions?.length) ? `'{${el?.actions?.map(action => `"${action}"`)}}'::text[]` : 'null'})`;
            sql.push(insertSql);
        });

        await pg.query(`insert into gis.services_users_rel (service_id,user_id,created_by,actions) values ${sql?.join(',')}`);
        return reply.status(201).send({ status: 201, message: `Inserted ${body?.length} permissions` });
    }
 catch (err) {
        return reply.status(500).send({ status: 500, message: err.toString() });
    }
}
