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

const serviceId = "hwlab-router";
const mode = process.env.HWLAB_ROUTER_MODE || "edge-reachability";
const edgeProxyService = process.env.HWLAB_EDGE_PROXY_SERVICE || "hwlab-edge-proxy";
const cloudApiService = process.env.HWLAB_CLOUD_API_SERVICE || "hwlab-cloud-api";
const { host, port } = resolveHostPort({
  listenEnv: "HWLAB_ROUTER_LISTEN",
  hostEnv: "HWLAB_ROUTER_HOST",
  portEnv: "HWLAB_ROUTER_PORT",
  fallbackPort: 7401
});

const routeTable = [
  {
    pathPrefix: "/health",
    targetServiceId: cloudApiService,
    mode: "local-health"
  },
  {
    pathPrefix: "/",
    targetServiceId: cloudApiService,
    via: edgeProxyService,
    mode: "dev-edge-reachability"
  }
];

const routes = new Map();

routes.set("GET /status", () => ({
  serviceId,
  environment: "dev",
  status: "ok",
  mode,
  edgeProxyService,
  cloudApiService,
  routeTable
}));

routes.set("GET /routes", () => ({
  serviceId,
  routeTable
}));

listen(
  createServiceServer({
    serviceId,
    role: "dev-router",
    routes,
    details: () => ({
      mode,
      edgeProxyService,
      cloudApiService,
      routeCount: routeTable.length
    })
  }),
  { serviceId, host, port }
);
