import db from '../../sql.mjs';
import lib from '../../lib.mjs';

export default router => {
  router.group(/^\/api\/v2\/settings/, group => {
    group.put(/\/setAvatar/, lib.loggedin, async (req, res) => {
      if(!req.post.avatar) {
        return res.json({
          msg: 'no avatar provided',
          debug: req.post
        }, 400); // bad request
      }

      const avatar = +req.post.avatar;

      const itemid = (await db`
        select id
        from "items"
        where id = ${+avatar} and active = 'true'
      `)?.[0]?.id;
      
      if(!itemid) {
        return res.json({
          msg: 'itemid not found'
        }, 404); // not found
      }

      const q = await db`
        update "user_options" set ${
          db({
            avatar
          }, 'avatar')
        }
        where user_id = ${+req.session.id}
      `;

      return res.json({
        msg: q
      }, 200);
    });

    return group;
  });

  return router;
};
