import db from "../../inc/sql.mjs";
import lib from "../lib.mjs";

export default (router, tpl) => {
  router.get(/^\/ranking$/, async (req, res) => {
    try {
      const list = await db`
        select
          "user".user,
          coalesce("user_options".avatar, ${await lib.getDefaultAvatar()}) as avatar,
          count(distinct(tag_id, item_id)) as count
        from "tags_assign"
        left join "user" on "user".id = "tags_assign".user_id
        left join "user_options" on "user_options".user_id = "user".id
        group by "user".user, "user_options".avatar
        order by count desc
      `;
      const stats = await lib.countf0cks();

      const hoster = await db`
        with t as (
          select
            split_part(substring(src, position('//' in src)+2), '/', 1) part
          from items
        )
        select t.part, count(t.part) as c
        from t
        group by t.part
        order by c desc
        limit 20
      `;

      const favotop = await db`
        select item_id, count(*) favs
        from favorites
        group by item_id
        having count(*) > 1
        order by favs desc
        limit 10
      `;

      res.reply({
        body: tpl.render('ranking', {
          list,
          stats,
          hoster,
          favotop,
          tmp: null
        }, req)
      });
    } catch(err) {
      res.end(JSON.stringify(err.message));
    }
  });

  return router;
};
