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

const allowedMimes = [ "audio", "image", "video" ];

export default (router, tpl) => {
  router.get(/^\/random\/?(?:user\/(?<user>[a-zA-Z0-9\[\]\-\_\{\}\\`\|]+))?(?:\/(?<mime>image|audio|video))?$/, async (req, res) => {
    const user    = req.params.user ?? null;
    const mime    = (req.params.mime ?? "");
    const smime   = allowedMimes.includes(mime) ? mime + "/%" : mime === "" ? "%" : "%";

    const modequery = mime == "audio" ? lib.getMode(0) : lib.getMode(req.session.mode ?? 0);

    if(user && (await sql("items").where("username", "like", user).count("* as total"))[0].total === 0)
      return res.end("200 - user not found lol");

    const rows = await sql("items")
      .select("id")
      .whereRaw(modequery)
      .andWhere("mime", "like", smime)
      .andWhere("username", "like", user ? user : "%")
      .orderByRaw("rand()")
      .limit(1);
    
    if(rows.length === 0)
      return res.end("nope");

    const link = lib.genLink({ user, mime });
  
    res.redirect(`/${link}${link.length != 0 ? "/": ""}${rows[0].id}`);
  });
  return router;
};
