import{FEEDBACK_API_URL as E}from"../../constants/common.js";import{MAX_AGENT_LENGTH as T,MAX_CONTEXT_LENGTH as A,MAX_EMAIL_LENGTH as k,MAX_LANG_LENGTH as y,MAX_PATH_LENGTH as N,MAX_REASONS_COUNT as F,MAX_TARGET_FEATURE_LENGTH as j}from"../../constants/feedback.js";import{mapObject as L}from"../../../utils/object/map-object.js";import{getFeedbackClientIp as C}from"../utils/feedback-ip.js";import{canAccessResource as R}from"../../utils/rbac.js";function r(n,e){if(n!=null)return String(n).replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,"").trim().slice(0,e)||void 0}function S(n){if(!n)return n;const e=["userAgent","firstName","lastName","auth_time","platform","id","email","ipAddress"];return L(n,(t,a)=>e.includes(a)?t:"*****")}function G({component:n,path:e,location:t,lang:a,agent:p,targetFeature:m,score:s,max:o,reasons:i,comment:f,metadata:l,email:h}){const u=Array.isArray(i)?i.map(c=>r(String(c),A)).filter(c=>!!c).slice(0,F):void 0;return{feedbackComponent:n.toUpperCase(),path:r(e,N),location:r(t,A),lang:r(a,y),score:typeof s=="number"?s:void 0,maxScore:typeof o=="number"?o:void 0,reasons:u?.length?u:void 0,comment:r(f,A),email:r(h,k),agent:r(p,T),targetFeature:r(m,j),metadata:S(l)}}async function M(n,e){return(await fetch(E,{method:"POST",body:JSON.stringify(G(n)),headers:e})).json()}function P(n){return async e=>{const t=await e.req.json(),a=e.req.header("user-agent"),p=C(e.req.raw),m=e.req.header("Sec-Ch-Ua-Platform"),s={...t.metadata,userAgent:a,ipAddress:p,platform:m?m.replace(/"/g,""):"unknown"},o=[];(!t.path||t.path==="")&&o.push("`path` is required");const i=["sentiment","rating","comment","problem","mood","scale"];if(i.includes(t.component)||o.push(`\`component\` field should be one of ${i.join(", ")}.`),o.length)return e.json({errors:o},400);const{claims:f,isAuthenticated:l,teams:h}=e.get("auth"),u={isAuthenticated:l,email:f?.email,teams:h};if(Object.keys(n.config.access?.rbac||{}).length>0){const d=t.path,_=new URL(d).pathname,b=n.getRouteBySlug(_);if(!b)return e.json({errors:["Resource not found"]},404);if(!R(b,u,n.config.access?.rbac,n.config.access?.requiresLogin))return e.json({errors:["Forbidden: no permission to send feedback for resource"]},403)}const c={"Content-Type":"application/json"},g=f?.email||t?.email||s?.email;try{const d=await M({...t,email:g,metadata:{email:g,...s}},c);return e.json({message:"Thanks for your feedback",...d},200,{})}catch(d){return e.json({errors:["Failed to send feedback",d.message]},500)}}}export{P as feedbackHandler,G as normalizeFeedbackData,S as normalizeFeedbackMetadata};
