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

export default async function userClsPost({
  pg = pgClients.client, body = {}, user = {},
}) {
  const { uid } = user || {};
  const {
    name, type = 'json', children = [], sql,
  } = body;

  if (!uid) {
    return { message: 'access restricted', status: 403 };
  }

  if (!name) {
    return { message: 'not enough params: name', status: 400 };
  }

  if (type === 'json' && (children?.length ? (!Array.isArray(children) || !children.length || !children?.[0]?.id) : false)) {
    return { message: 'invalid params: children (array of objects)', status: 400 };
  }

  if (type === 'sql' && (!sql || typeof sql !== 'string')) {
    return { message: 'invalid params: sql (string)', status: 400 };
  }


  const { rowCount = 0 } = await pg.query(`with recursive rows as (
      select user_clsid, name, code, icon, color, parent
      from admin.user_cls a
      where name=$1
      union all
      select a.user_clsid, a.name, a.code, a.icon, a.color, a.parent
      from admin.user_cls a
      join rows b on a.parent=b.name
    ) delete from admin.user_cls where user_clsid in (select user_clsid from rows )`, [name]);
  console.log('delete old user cls', name, rowCount);

  const { id, data } = await pg.query('insert into admin.user_cls(name,type,data,uid) values($1,$2,$3,$4) returning user_clsid as id, data', [name, type, sql, uid])
    .then((res) => res.rows?.[0] || {});
  if (type === 'json' && children?.length) {
    if (!id) { return { error: 'insert user cls error', status: 500 }; }
    const q1 = `insert into admin.user_cls(code,name,color,icon,parent,uid)
      
      select value->>'id',value->>'text',value->>'color',value->>'icon', '${name.replace(/'/g, "''")}', '${uid}'
      from json_array_elements('${JSON.stringify(children).replace(/'/g, "''")}'::json)
      
      returning user_clsid as id, code, name, parent`;
    const { rows = [] } = await pg.query(q1);
    return { id, name, type, children: rows };
  }
  return { id, name, type, data };

}
