import {
  getFileHit as dbGetFileHit,
  getPostedFileName as dbGetPostedFileName,
  postFileHit,
} from "@/app/www/system/DB";
import { ESSAY_ENTRY_PATH } from "@/app/www/utilities/Path";
import { isBannedIP } from "@/app/www/utilities/Utility";
import { readFile } from "fs/promises";
import { join } from "path";
import { getDate } from "taehui-lib/date";

export const getFile = async (fileName: string, avatarIP: string) => {
  return (
    await Promise.all([
      isBannedIP(avatarIP) ||
      fileName.match(/^.*\.(bmp|gif|jpeg|jpg|png|webp)$/i) ||
      fileName.match(
        /^.*\.(aif|aiff|asf|flac|m4a|mid|midi|mp2|mp3|ogg|opus|raw|wav|wma)$/i,
      ) ||
      fileName.match(/^.*\.(avi|flv|m1v|mkv|mov|mp4|mpeg|mpg|webm|wmv)$/i)
        ? Promise.resolve()
        : postFileHit(fileName, avatarIP, getDate()),
      readFile(join(ESSAY_ENTRY_PATH, fileName)),
    ])
  )[1];
};

export const getPostedFileName = async (fileName: string) => {
  return dbGetPostedFileName(fileName);
};

export const getFileHit = async (fileName: string) => {
  return dbGetFileHit(fileName);
};
