import Koa from "koa";
import koaHelmet from "koa-helmet";
import { readdirSync, unlinkSync } from "fs";
import { join } from "path";

import routers from "src/routers";
import DB from "src/system/DB";
import Logger from "src/system/Logger";
import Configure from "src/system/Configure";

const koa = new Koa();

koa.use(koaHelmet());

koa.use(async (ctx, next) => {
  const {
    request,
    request: { method, url, headers },
  } = ctx;

  if (headers["x-real-ip"]) {
    request.ip = headers["x-real-ip"] as string;
  }

  const { ip } = request;

  try {
    await next();
  } catch (e) {
    Logger.error(e);
    ctx.status = 500;
  } finally {
    const { status } = ctx;
    Logger.info(`[${ip}] ${method} ${url} ${status}`);
  }
});

koa.use(routers.routes());

(async () => {
  await DB.loadDB();

  const fileNames = readdirSync(Configure.path.essay);
  for (const fileName of fileNames) {
    if (!(await DB.isValidFile(fileName))) {
      unlinkSync(join(Configure.path.essay, fileName));
      Logger.info(`Wiped ${fileName}`);
    }
  }

  const taehui = koa.listen(10100, () => {
    process.send?.("ready");
    Logger.info("Loaded Taehui");
  });

  process.on("SIGINT", () => {
    taehui.close((err) => {
      process.exit(err ? 1 : 0);
    });
  });
})();
