import { promises as fs } from "fs";
import db from "../sql.mjs";
import { getLevel } from "../../inc/admin.mjs";

export default async bot => {

  return [{
    name: "delete",
    call: /^\!(del|rm) .*/i,
    active: true,
    f: async e => {
      let deleted = [];

      for(let id of e.args) {
        id = +id;
        if(id <= 1)
          continue;
        
        const f0ck = await db`
          select dest, username, userchannel, usernetwork
          from "items"
          where id = ${id}
          limit 1
        `;
        const level = getLevel(e.user).level;

        if(f0ck.length === 0) {
          e.reply(`f0ck ${id}: f0ck not found`);
          continue;
        }
        
        if(
          (f0ck[0].username !== (e.user.nick || e.user.username) ||
          f0ck[0].userchannel !== e.channel ||
          f0ck[0].usernetwork !== e.network) &&
          level < 100
        ) {
          e.reply(`f0ck ${id}: insufficient permissions`);
          continue;
        }

        if(~~(new Date() / 1e3) >= (f0ck[0].stamp + 600) && level < 100) {
          e.reply(`f0ck ${id}: too late lol`);
          continue;
        }

        await fs.unlink(`./public/b/${f0ck[0].dest}`).catch(_=>{});
        await fs.unlink(`./public/t/${id}`).catch(_=>{});

        await db`
          delete from "items"
          where id = ${+id}
        `;

        deleted.push(id);
      }

      e.reply(`deleted ${deleted.length}/${e.args.length} f0cks (${deleted.join(",")})`);
    }
  }]
};
