import{JWT_SECRET_KEY as s}from"../../constants/common.js";import*as i from"../jwt/jwt.js";const o=(e,r)=>e.secureMethods?.includes(r)??!1;function l(e={}){return async(r,a)=>{const n=r.req.method;return o(e,n)?await c(r,a):await a()}}const c=async(e,r)=>{const a=e.req.header("apiKey");if(a)return await d(e,r,a);const t=e.req.header("authorization")?.replace("Bearer ","");return t?await u(e,r,t):e.json({message:"API key is required"},401)},d=async(e,r,a)=>{if(!process.env.BH_API_URL)return e.json({message:"API key validation service not configured"},500);try{const n=new URL("/api/api-keys-verify",process.env.BH_API_URL).toString();return(await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:a})})).ok?await r():e.json({message:"Invalid API key"},401)}catch{return e.json({message:"API key validation failed"},400)}},u=async(e,r,a)=>{try{const n=await i.verify(a,s),t=i.decode(a).payload.isInternalConnection;return!n||!t?e.json({message:"API key is required"},401):await r()}catch{return e.json({message:"API key validation failed"},400)}};export{l as catalogAuthMiddleware};
