import f0cklib from "./inc/f0cklib.mjs";

export default (router, tpl) => {
  router.get(/^\/random$/, async (req, res) => {
    let referer = req.headers.referer ?? '';
    let opts = {};

    if(referer.match(/f0ck\.me/)) { // parse referer
      referer = referer.split("f0ck.me")[1];
      const tmp = referer.match(/^\/?(?:\/tag\/(?<tag>.+?))?(?:\/user\/(?<user>.+?)\/(?<mode>f0cks|favs))?(?:\/(?<mime>image|audio|video))?(?:\/p\/(?<page>\d+))?(?:\/(?<itemid>\d+))?$/);
      if(tmp)
        opts = tmp.groups;
    }

    const data = await f0cklib.getRandom({
      user: opts.user,
      tag: opts.tag,
      mime: opts.mime,
      page: opts.page,
      fav: opts.mode == 'favs',
      mode: req.session.mode
    });

    if(!data.success) {
      return res.reply({
        code: 404,
        body: tpl.render('error', {
          message: data.message,
          tmp: null
        }, req)
      });
    }

    res.redirect(`/${data.link}${data.link.length != 0 ? "/" : ""}${data.itemid}`);
  });
  return router;
};
