import { NextFunction, Request, Response } from "express";

let warnedNoSecretConfigured = false;

// Deferred by design: the upstream shared-secret contract isn't finalized
// yet. With UPSTREAM_API_SECRET unset (the v1 default), every request is
// allowed through and a warning is logged once at startup. Set the env var
// to start enforcing the real Bearer-token check.
export function requireUpstreamSecret(req: Request, res: Response, next: NextFunction): void {
  const expected = process.env.UPSTREAM_API_SECRET;

  if (!expected) {
    if (!warnedNoSecretConfigured) {
      console.warn(
        "UPSTREAM_API_SECRET is not set -- auth is disabled, all requests are accepted. This is a v1 placeholder, not for production."
      );
      warnedNoSecretConfigured = true;
    }
    next();
    return;
  }

  const header = req.get("Authorization") ?? "";
  const [scheme, token] = header.split(" ");

  if (scheme !== "Bearer" || token !== expected) {
    res.status(401).json({ error: { code: "UNAUTHORIZED", message: "Missing or invalid bearer token" } });
    return;
  }

  next();
}
