#!/usr/bin/env node
import {
  createServiceServer,
  listen,
  parsePort,
  resolveHostPort
} from "../../internal/dev-entrypoint/http.mjs";

const serviceId = "hwlab-tunnel-client";
const mode = process.env.HWLAB_TUNNEL_MODE || "frp-client";
const serverAddress = process.env.HWLAB_FRP_SERVER_ADDR || "74.48.78.17";
const publicPort = parsePort(process.env.HWLAB_FRP_PUBLIC_PORT, 16667);
const webPublicPort = parsePort(process.env.HWLAB_FRP_WEB_PUBLIC_PORT, 16666);
const localService = process.env.HWLAB_TUNNEL_LOCAL_SERVICE || "hwlab-edge-proxy";
const localPort = parsePort(process.env.HWLAB_TUNNEL_LOCAL_PORT, 6667);
const { host, port } = resolveHostPort({
  listenEnv: "HWLAB_TUNNEL_LISTEN",
  hostEnv: "HWLAB_TUNNEL_HOST",
  portEnv: "HWLAB_TUNNEL_PORT",
  fallbackPort: 7402
});

function tunnelState() {
  return {
    serviceId,
    environment: "dev",
    status: "configured",
    mode,
    reverseLink: {
      direction: "d601-to-master",
      serverAddress,
      publicPort,
      webPublicPort,
      localService,
      localPort
    },
    liveConnection: "not_started_by_entrypoint"
  };
}

const routes = new Map();
routes.set("GET /status", () => tunnelState());
routes.set("GET /tunnel", () => tunnelState().reverseLink);

listen(
  createServiceServer({
    serviceId,
    role: "frp-client",
    routes,
    details: () => tunnelState()
  }),
  { serviceId, host, port }
);
