import { Router } from "@fastly/expressly";
import { getGeolocationForIpAddress } from "fastly:geolocation";

const router = new Router();

router.get("(.*)", async (req, res) => {
  let geo;
  try {
    geo = getGeolocationForIpAddress(req.ip);
  } catch (error) {
    console.error(error);
  }

  let offset = geo.utc_offset;
  // Add TZ in ISO8601 format
  let tz_offset_iso8601 = offset;
  req.headers.append("tz-offset-iso8601", tz_offset_iso8601);

  // Round to a whole hour
  let tz_hour = Math.round(offset / 100);
  req.headers.append("tz-hour", tz_hour);

  // Parse the time offset into a decimal number of hours
  let tz_offset_hours = (offset % 100) / 60 + Math.round(offset / 100);
  req.headers.append("tz-offset-hours", tz_offset_hours);

  // Round to nearest even hour
  let tz_evenhour = Math.round(offset / 100 / 2) * 2;
  req.headers.append("tz-evenhour", tz_evenhour);

  // send backend response to client
  res.send(await fetch(req, { backend: "origin_0" }));
});

router.listen();