import cfg from "../config.mjs";
import db from "../sql.mjs";
import lib from "../lib.mjs";
import f0cklib from "../routeinc/f0cklib.mjs";

const auth = async (req, res, next) => {
  if(!req.session)
    return res.redirect("/login");
  return next();
};

export default (router, tpl) => {
  router.get(/\/user\/(?<user>.*)/, lib.loggedin, async (req, res) => {
    const user = decodeURIComponent(req.params.user);

    const query = await db`
      select "user".user, "user".admin, "user".created_at, user_options.*
      from user_options
      left join "user" on "user".id = user_options.user_id
      where "user".user ilike ${user}
      limit 1
    `;

    if(!query.length) {
      return res.reply({
        code: 404,
        body: tpl.render('error', {
          message: 'this user does not exists',
          tmp: null
        }, req)
      });
    }

    let f0cks, favs;
    const count = {
      f0cks: 0,
      favs: 0
    };
    try {
      f0cks = await f0cklib.getf0cks({
        user: user,
        mode: req.session.mode,
        fav: false,
        session: !!req.session,
        limit: 99999999
      });
      if('items' in f0cks) {
        count.f0cks = f0cks.items.length;
        f0cks.items = f0cks.items.slice(0, 50);
      }
    } catch(err) {
      f0cks = false;
      count.f0cks = 0;
    }
    try {
      favs = await f0cklib.getf0cks({
        user: user,
        mode: req.session.mode,
        fav: true,
        session: !!req.session,
        limit: 99999999
      });
      if('items' in favs) {
        count.favs = favs.items.length;
        favs.items = favs.items.slice(0, 50);
      }
    } catch(err) {
      favs = false;
      count.favs = 0;
    }

    const data = {
      user: query[0],
      f0cks,
      count,
      favs,
      tmp: null
    };

    return res.reply({ body: tpl.render('user', data, req) });
  });

  router.get(/^\/?(?:\/tag\/(?<tag>.+?))?(?:\/user\/(?<user>.+?)\/(?<mode>f0cks|favs))?(?:\/(?<mime>image|audio|video))?(?:\/p\/(?<page>\d+))?(?:\/(?<itemid>\d+))?$/, async (req, res) => {
    const mode = req.params.itemid ? 'item' : 'index';
    if(mode === 'item' && !req.session)
      return res.redirect('/login');
    
    const data = await (req.params.itemid ? f0cklib.getf0ck : f0cklib.getf0cks)({
      user: req.params.user,
      tag: req.params.tag,
      mime: req.params.mime,
      page: req.params.page,
      itemid: req.params.itemid,
      fav: req.params.mode == 'favs',
      mode: req.session.mode,
      session: !!req.session
    });
    if(!data.success) {
      return res.reply({
        code: 404,
        body: tpl.render('error', {
          message: data.message,
          tmp: null
        }, req)
      });
    }

    return res.reply({ body: tpl.render(mode, data, req) });
  });

  router.get(/^\/(about)$/, (req, res) => {
    res.reply({
      body: tpl.render(req.url.split[0], { tmp: null }, req)
    });
  });

  router.get(/^\/mode\/(\d)/, lib.loggedin, async (req, res) => {
    const mode = +req.url.split[1];
    let referertmp = req.headers.referer;
    let referer = "";

    if(referertmp?.match(/f0ck\.me/))
      referer = referertmp.split("/").slice(3).join("/");

    if(cfg.allowedModes[mode]) {
      const blah = {
        user_id: req.session.id,
        mode: mode,
        theme: req.theme ?? "f0ck"
      };

      await db`
        insert into "user_options" ${
          db(blah, 'user_id', 'mode', 'theme')
        }
        on conflict ("user_id") do update set
          mode = excluded.mode,
          theme = excluded.theme,
          user_id = excluded.user_id
      `;
    }
    res.redirect(`/${referer}`);
  });

  return router;
};
