const { Reader } = require("@maxmind/geoip2-node");
import * as path from "path";

let geoReader: any;

const loadReader = async (): Promise<any> => {
  const dbPath = path.join(__dirname, "GeoLite2-Country.mmdb");
  console.log(dbPath);

  geoReader = geoReader || (await Reader.open(dbPath));
  return geoReader;
}

const handler = async (req: any, res: any) => {
  const reader = await loadReader();

  const forwardedFor = req.headers["x-forwarded-for"];
  const ips = forwardedFor ? forwardedFor.split(",") : [];
  const ip = ips[0] || req.connection.remoteAddress;

  try {
    const geo = reader.country(ip);
    res.status(200).json({
      lang: geo.country.names.en === "Vietnam" ? "vi" : "en",
      info: { ...{ip} }
    });
  } catch(err) {
    console.error(err);
    res.status(200).json({
      lang: "en",
      info: { ...{ip}, err }
    });
  }
}

module.exports = handler;
