import { Router } from "express";
import fs from "fs";

const router = Router();

router.get("/", async (req, res) => {
  const ip = req.headers["x-forwarded-for"];

  try {
    const { countryCode, region, regionName }: any = await (
      await fetch(`http://ip-api.com/json/${ip}?lang=ru`)
    ).json();

    if (countryCode === "RU") {
      fs.appendFileSync(
        "./log.txt",
        `${countryCode}-${region} (${regionName})\n`
      );
    }

    res.json({ regionName });
  } catch (error) {
    if (error instanceof Error) {
      res.json({ error: error.message });
    }
  }
});

const getRegionNameRoute = router;

export default getRegionNameRoute;
