import koaBody from "koa-body";
import Router from "koa-router";
import { parse } from "path";
import { validateTotem } from "src/mws/avatar";
import { validateMillis } from "src/mws/millis";
import Configure from "src/system/Configure";
import { getFile, getFileHit, getPostedFileName } from "src/systems/file";

const router = new Router();

router.post(
  "/",
  validateMillis,
  validateTotem(false),
  async (ctx, next) => {
    try {
      const { postLength } = Configure;
      await koaBody({
        multipart: true,
        formidable: {
          keepExtensions: true,
          uploadDir: Configure.path.essay,
          maxFileSize: postLength,
          maxFieldsSize: postLength,
        },
      })(ctx, next);
    } catch (e: any) {
      if (e?.httpCode) {
        ctx.status = e.httpCode;
      }
    }
  },
  async (ctx) => {
    const {
      request: { files },
    } = ctx;

    if (files) {
      const { data } = files;
      const { base } = parse((Array.isArray(data) ? data[0] : data).filepath);
      ctx.body = { fileName: base };
      ctx.status = 201;
    } else {
      ctx.status = 403;
    }
  },
);

router.get("/:fileName", async (ctx) => {
  const {
    request: { ip },
    params: { fileName },
  } = ctx;

  ctx.set(
    "content-disposition",
    `attachment; filename="${encodeURI(
      (await getPostedFileName(fileName)) ?? fileName,
    )}"`,
  );
  ctx.body = await getFile(fileName, ip);
  ctx.status = 200;
});

router.get("/:fileName/hit", async (ctx) => {
  const {
    params: { fileName },
  } = ctx;

  ctx.body = await getFileHit(fileName);
  ctx.status = 200;
});

export default router;
