import type { Request, Response, NextFunction } from "express";
import { GraphQLClient } from "graphql-request";

// Attach a per-request GraphQL client with dynamic headers (e.g., auth)
interface GraphQLAugmentedRequest extends Request {
  gql?: GraphQLClient;
}

export function attachGraphQLClient(
  req: Request,
  _res: Response,
  next: NextFunction
) {
  const endpoint =
    process.env.GO_GRAPHQL_URL || "http://localhost:8080/graphql";
  const headers: Record<string, string> = {};

  // Propagate Authorization header if present
  if (req.headers.authorization) {
    headers["authorization"] = req.headers.authorization;
  }

  // TODO[P2]: Add request-scoped correlation ID / tracing headers

  (req as GraphQLAugmentedRequest).gql = new GraphQLClient(endpoint, {
    headers,
  });
  next();
}
