import{FEEDBACK_API_URL as k}from"../../constants/common.js";import{mapObject as j}from"../../../utils/object/map-object.js";import{getClientIp as y}from"../utils/get-client-ip.js";import{canAccessResource as A}from"../../utils/rbac.js";function w(n){if(!n)return n;const e=["userAgent","firstName","lastName","auth_time","platform","id","email","ipAddress"];return j(n,(o,a)=>e.includes(a)?o:"*****")}function C({component:n,path:e,location:o,lang:a,score:d,max:s,reasons:i,comment:r,metadata:c,email:m}){return{feedbackComponent:n.toUpperCase(),path:e,location:o,lang:a,score:d,maxScore:s,reasons:i,comment:r,email:m,metadata:w(c)}}async function F(n,e){return(await fetch(k,{method:"POST",body:JSON.stringify(C(n)),headers:e})).json()}function U(n){return async e=>{const o=await e.req.json(),a=e.req.header("user-agent"),d=y(e.req.raw),s=e.req.header("Sec-Ch-Ua-Platform"),i={...o.metadata,userAgent:a,ipAddress:d,platform:s?s.replace(/"/g,""):"unknown"},r=[];(!o.path||o.path==="")&&r.push("`path` is required");const c=["sentiment","rating","comment","problem","mood","scale"];if(c.includes(o.component)||r.push(`\`component\` field should be one of ${c.join(", ")}.`),r.length)return e.json({errors:r},400);const{claims:m,isAuthenticated:u,teams:l}=e.get("auth"),h={isAuthenticated:u,email:m?.email,teams:l};if(Object.keys(n.config.rbac||{}).length>0){const t=o.path,g=new URL(t).pathname,p=n.getRouteBySlug(g);if(!p)return e.json({errors:["Resource not found"]},404);if(!A(p,h,n.config.rbac,n.config.requiresLogin))return e.json({errors:["Forbidden: no permission to send feedback for resource"]},403)}const b={"Content-Type":"application/json"},f=m?.email||o?.email||i?.email;try{const t=await F({...o,email:f,metadata:{email:f,...i}},b);return e.json({message:"Thanks for your feedback",...t},200,{})}catch(t){return e.json({errors:["Failed to send feedback",t.message]},500)}}}export{U as feedbackHandler,w as normalizeFeedbackMetadata};
