import db from "../sql.mjs";
import lib from "../lib.mjs";
import search from "../routeinc/search.mjs";

export default (router, tpl) => {
  router.get(/^\/search(\/)?$/, lib.auth, async (req, res) => {
    let ret;
    let tag = req.url.qs?.tag;
    if(Object.keys(req.url.qs).length > 0) {
      let rows;

      if(tag.startsWith('src:')) {
        tag = tag.substring(4);
        ret = await db`
          select *
          from "items"
          where src ilike ${'%' + tag + '%'}
          limit 500
        `;
      }
      else {
        rows = await db`
          select "items".id, "items".username, "items".mime, "tags".tag
          from "tags"
          left join "tags_assign" on "tags_assign".tag_id = "tags".id
          left join "items" on "items".id = "tags_assign".item_id
          where "tags".tag ilike ${'%' + tag + '%'}
          limit 500
        `;
        ret = search(rows, tag);
      }
    }
  
    res.reply({
      body: tpl.render("search", {
        result: ret,
        totals: await lib.countf0cks(),
        searchstring: tag,
        session: req.session,
        tmp: null
      }, req)
    });
  });
};
