import { posthog } from "../analytics.js"
import { logger } from "../utils/logger.js"

// Middleware to log endpoint calls
export function trackEndpointCalls(req, res, next) {
  // Use endpoint from req.endpoint (set by enhanced-logging middleware) or fallback
  const endpoint = req.endpoint || req.path || req.url || "unknown"
  const context = {
    requestId: req.requestId,
    traceId: req.traceId,
    endpoint,
    operation: "endpoint_call",
    userId: req.userId,
  }
  // Always log endpoint calls (logger handles environment filtering)
  logger.info("Endpoint called", context, {
    method: req.method,
    ...(req.get("User-Agent") && { userAgent: req.get("User-Agent") }),
    ...(req.ip && { ip: req.ip }),
  })

  posthog?.capture({
    distinctId: req.userId,
    event: `cfapi-endpoint-called-${req.path}`,
  })
  next()
}
