import db from "../../inc/sql.mjs";
import cfg from "../../inc/config.mjs";

export default (router, tpl) => {
  router.get(/^\/tags$/, async (req, res) => {

    const phrase = cfg.websrv.phrases[~~(Math.random() * cfg.websrv.phrases.length)];

    const nsfp = cfg.nsfp.map(n => `${n}`);

    const toptags = await db`
      SELECT t.id, t.tag, COUNT(DISTINCT ta.item_id) AS total_items
      FROM tags t
      LEFT JOIN tags_assign ta ON t.id = ta.tag_id
      WHERE t.id not in (${db.unsafe(nsfp)})
      GROUP BY t.id, t.tag
      ORDER BY total_items DESC
      LIMIT 500
      ;
    `;

    const toptags_regged = await db`
      SELECT t.id, t.tag, COUNT(DISTINCT ta.item_id) AS total_items
      FROM tags t
      LEFT JOIN tags_assign ta ON t.id = ta.tag_id
      GROUP BY t.id, t.tag
      ORDER BY total_items DESC
      LIMIT 500
      ;
    `;
    
    res.reply({
      body: tpl.render('tags', {
        toptags,
        toptags_regged,
        phrase,
        tmp: null
      }, req)
    });
  });
  return router;
};
