'use strict';

// Public routes are intentionally limited to external ingress. Telemetry admin
// routes are public only at this outer gate; api-walle enforces
// WALLE_TELEMETRY_SECRET before returning any data.
const PUBLIC_ROUTES = new Set([
  '/api/wall-e/health',
  '/api/wall-e/webhook',
  '/api/wall-e/telemetry/ingest',
  '/api/wall-e/telemetry/summary',
  '/api/wall-e/telemetry/storage',
  '/api/wall-e/telemetry/cleanup',
  '/api/wall-e/telemetry/events',
  '/api/wall-e/telemetry/feedback',
]);

function getAllowedOrigin(req) {
  const ctmPort = process.env.CTM_PORT || '3456';
  if (process.env.CTM_ORIGIN) return process.env.CTM_ORIGIN;
  const origin = req?.headers?.origin;
  const allowed = new Set([
    `http://127.0.0.1:${ctmPort}`,
    `http://localhost:${ctmPort}`,
  ]);
  return allowed.has(origin) ? origin : `http://127.0.0.1:${ctmPort}`;
}

function isLocalRequest(req) {
  const addr = String(req?.socket?.remoteAddress || '');
  return addr === '127.0.0.1' || addr === '::1' || addr === '::ffff:127.0.0.1';
}

function requireBearer(req, token) {
  return !!token && req?.headers?.authorization === `Bearer ${token}`;
}

function isPublicRoute(pathname) {
  return PUBLIC_ROUTES.has(pathname);
}

function isAuthorizedRequest(req, pathname, token) {
  if (isPublicRoute(pathname)) return true;
  return isLocalRequest(req) || requireBearer(req, token);
}

module.exports = {
  PUBLIC_ROUTES,
  getAllowedOrigin,
  isAuthorizedRequest,
  isLocalRequest,
  isPublicRoute,
  requireBearer,
};
