import fs from "fs";
import { fileURLToPath } from "url";
import path from "path";
import ipCheck from "ip";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ipDir = path.join(__dirname, "./ip_ranges");

const database = {};
for (const file of fs.readdirSync(ipDir)) {
  database[path.basename(file, ".json")] = JSON.parse(
    fs.readFileSync(path.join(ipDir, file)).toString()
  )["NN"].map(({ prefix }) => prefix);
}

export const checkIp = (ip) => {
  for (const [name, cidrs] of Object.entries(database)) {
    for (const cidr of cidrs) {
      if (ipCheck.cidrSubnet(cidr).contains(ip)) {
        return name;
      }
    }
  }
  return null;
};
