"use strict";(()=>{var a={};a.id=89459,a.ids=[89459],a.modules={51455:a=>{a.exports=require("node:fs/promises")},161730:(a,b,c)=>{Object.defineProperty(b,"I",{enumerable:!0,get:function(){return g}});let d=c(554226),e=c(884327),f=c(728392);async function g(a,b,c,g){if((0,d.isNodeNextResponse)(b)){var h;b.statusCode=c.status,b.statusMessage=c.statusText;let d=["set-cookie","www-authenticate","proxy-authenticate","vary"];null==(h=c.headers)||h.forEach((a,c)=>{if("x-middleware-set-cookie"!==c.toLowerCase())if("set-cookie"===c.toLowerCase())for(let d of(0,f.splitCookiesString)(a))b.appendHeader(c,d);else{let e=void 0!==b.getHeader(c);(d.includes(c.toLowerCase())||!e)&&b.appendHeader(c,a)}});let{originalResponse:i}=b;c.body&&"HEAD"!==a.method?await (0,e.pipeToNodeResponse)(c.body,i,g):i.end()}}},176760:a=>{a.exports=require("node:path")},200261:a=>{a.exports=require("next/dist/shared/lib/router/utils/app-paths")},257975:a=>{a.exports=require("node:util")},321947:(a,b,c)=>{c.r(b),c.d(b,{handler:()=>F,patchFetch:()=>E,routeModule:()=>A,serverHooks:()=>D,workAsyncStorage:()=>B,workUnitAsyncStorage:()=>C});var d={};c.r(d),c.d(d,{GET:()=>z,dynamic:()=>w,runtime:()=>x});var e=c(940527),f=c(41752),g=c(633335),h=c(573615),i=c(301769),j=c(200261),k=c(405563),l=c(439285),m=c(443399),n=c(295860),o=c(161730),p=c(728392),q=c(976618),r=c(406527),s=c(986439),t=c(975973),u=c(612839),v=c(567472);let w="force-dynamic",x="nodejs",y=new Set(["person","all","automated"]);async function z(a){let b=new URL(a.url),c=b.searchParams.get("q")?.trim().toLowerCase()??"",d=b.searchParams.get("sender")??"person",e=y.has(d)?d:"person",f=b.searchParams.get("personId")?.trim()||null,g=function(a,b,c){let d=a?parseInt(a,10):NaN;return!Number.isFinite(d)||d<=0?50:Math.min(d,200)}(b.searchParams.get("limit"),50,200),h=Math.max(0,parseInt(b.searchParams.get("offset")??"0",10)||0),i=await (0,v.y3)(),j=(0,v.gt)({objectId:u.zq.email_thread,fieldMap:i.email_thread,aliasedFields:[{name:"Subject",alias:"subject"},{name:"Last Message At",alias:"last_message_at"},{name:"Message Count",alias:"message_count"},{name:"Gmail Thread ID",alias:"gmail_thread_id"},{name:"Participants",alias:"participants_json"}]}),k="1=1";if(c){let a=c.replace(/'/g,"''");k+=` AND LOWER(COALESCE(subject, '')) LIKE '%${a}%'`}if(f){let a=f.replace(/"/g,'""').replace(/'/g,"''");k+=` AND participants_json LIKE '%"${a}"%'`}let l=i.email_message.Thread,m=i.email_message["Sent At"],n=i.email_message["Sender Type"],o=i.email_message["Body Preview"],p=i.email_message.From,q=Math.max(5*g,250),r=!!(l&&m),s=r?`
        , candidate_threads AS (
          SELECT entry_id FROM base
          WHERE ${k}
          ORDER BY last_message_at DESC NULLS LAST
          LIMIT ${q}
        ),
        latest_msg AS (
          SELECT
            thread_value AS thread_id,
            ${n?"ARG_MAX(sender_type_value, sent_at_value)":"NULL"} AS sender_type,
            ${o?"ARG_MAX(preview_value, sent_at_value)":"NULL"} AS snippet,
            ${p?"ARG_MAX(from_value, sent_at_value)":"NULL"} AS from_person_id
          FROM (
            SELECT
              e.id AS msg_id,
              MAX(CASE WHEN ef.field_id = '${l}' THEN ef.value END) AS thread_value,
              MAX(CASE WHEN ef.field_id = '${m}' THEN ef.value END) AS sent_at_value,
              ${n?`MAX(CASE WHEN ef.field_id = '${n}' THEN ef.value END)`:"NULL"} AS sender_type_value,
              ${o?`MAX(CASE WHEN ef.field_id = '${o}' THEN ef.value END)`:"NULL"} AS preview_value,
              ${p?`MAX(CASE WHEN ef.field_id = '${p}' THEN ef.value END)`:"NULL"} AS from_value
            FROM entries e
            JOIN entry_fields ef
              ON ef.entry_id = e.id
             AND ef.field_id IN ('${l}', '${m}'
               ${n?`, '${n}'`:""}
               ${o?`, '${o}'`:""}
               ${p?`, '${p}'`:""})
            WHERE e.object_id = '${u.zq.email_message}'
            GROUP BY e.id
          ) m
          WHERE m.thread_value IN (SELECT entry_id FROM candidate_threads)
          GROUP BY thread_value
        )
      `:"",t="";r&&"person"===e?t="AND (latest_msg.sender_type IS NULL OR latest_msg.sender_type = 'Person')":r&&"automated"===e&&(t="AND latest_msg.sender_type IS NOT NULL AND latest_msg.sender_type <> 'Person'");let w=`
    WITH base AS (${j})
    ${s}
    SELECT
      base.*,
      ${r?"latest_msg.sender_type AS sender_type, latest_msg.snippet AS snippet, latest_msg.from_person_id AS from_person_id":"NULL AS sender_type, NULL AS snippet, NULL AS from_person_id"},
      COUNT(*) OVER () AS _total
    FROM base
    ${r?"LEFT JOIN latest_msg ON latest_msg.thread_id = base.entry_id":""}
    WHERE ${k}
      ${t}
    ORDER BY base.last_message_at DESC NULLS LAST
    LIMIT ${g} OFFSET ${h};
  `,x=await (0,v.Ez)(w),z=x[0]?._total?Number(x[0]._total):0,A=new Set,B=x.map(a=>{let b=function(a){if(!a)return[];let b=a.trim();if(!b)return[];if(b.startsWith("["))try{let a=JSON.parse(b);if(Array.isArray(a))return a.map(String).filter(Boolean)}catch{}return[b]}(a.participants_json);for(let a of b)A.add(a);return a.from_person_id&&A.add(a.from_person_id),{id:String(a.entry_id),subject:a.subject,last_message_at:a.last_message_at,message_count:a.message_count?Number(a.message_count):null,gmail_thread_id:a.gmail_thread_id,participant_ids:b,snippet:a.snippet,primary_sender_type:a.sender_type,primary_sender_id:a.from_person_id??null}}),C=i.people["Full Name"],D=i.people["Email Address"],E=i.people["Avatar URL"],F=new Map;if(A.size>0&&(C||D)){let a=Array.from(A).map(a=>`'${a.replace(/'/g,"''")}'`).join(", "),b=`
      SELECT
        e.id AS person_id,
        ${C?`MAX(CASE WHEN ef.field_id = '${C}' THEN ef.value END)`:"NULL"} AS name,
        ${D?`MAX(CASE WHEN ef.field_id = '${D}' THEN ef.value END)`:"NULL"} AS email,
        ${E?`MAX(CASE WHEN ef.field_id = '${E}' THEN ef.value END)`:"NULL"} AS avatar_url
      FROM entries e
      LEFT JOIN entry_fields ef ON ef.entry_id = e.id
      WHERE e.object_id = '${u.zq.people}'
        AND e.id IN (${a})
      GROUP BY e.id;
    `;for(let a of(await (0,v.Ez)(b)))F.set(a.person_id,{id:a.person_id,name:a.name,email:a.email,avatar_url:a.avatar_url})}let G=B.map(a=>{let b=new Set,c=[];if(a.primary_sender_id){let d=F.get(a.primary_sender_id);d&&(c.push(d),b.add(d.id))}for(let d of a.participant_ids){if(b.has(d))continue;let a=F.get(d);a&&(c.push(a),b.add(d))}let d=a.primary_sender_id?F.get(a.primary_sender_id):void 0;return{id:a.id,subject:a.subject,last_message_at:a.last_message_at,message_count:a.message_count,gmail_thread_id:a.gmail_thread_id,participant_ids:a.participant_ids,participants:c,snippet:a.snippet,primary_sender_type:a.primary_sender_type,primary_sender_id:d?.id??null,primary_sender_name:d?.name??null,primary_sender_email:d?.email??null}});return Response.json({threads:G,total:z,limit:g,offset:h,sender:e})}let A=new e.AppRouteRouteModule({definition:{kind:f.RouteKind.APP_ROUTE,page:"/api/crm/inbox/route",pathname:"/api/crm/inbox",filename:"route",bundlePath:"app/api/crm/inbox/route"},distDir:".next",relativeProjectDir:"",resolvedPagePath:"/home/runner/work/DenchClaw/DenchClaw/apps/web/app/api/crm/inbox/route.ts",nextConfigOutput:"standalone",userland:d}),{workAsyncStorage:B,workUnitAsyncStorage:C,serverHooks:D}=A;function E(){return(0,g.patchFetch)({workAsyncStorage:B,workUnitAsyncStorage:C})}async function F(a,b,c){var d;let e="/api/crm/inbox/route";"/index"===e&&(e="/");let g=await A.prepare(a,b,{srcPage:e,multiZoneDraftMode:!1});if(!g)return b.statusCode=400,b.end("Bad Request"),null==c.waitUntil||c.waitUntil.call(c,Promise.resolve()),null;let{buildId:u,params:v,nextConfig:w,isDraftMode:x,prerenderManifest:y,routerServerContext:z,isOnDemandRevalidate:B,revalidateOnlyGenerated:C,resolvedPathname:D}=g,E=(0,j.normalizeAppPath)(e),F=!!(y.dynamicRoutes[E]||y.routes[D]);if(F&&!x){let a=!!y.routes[D],b=y.dynamicRoutes[E];if(b&&!1===b.fallback&&!a)throw new s.NoFallbackError}let G=null;!F||A.isDev||x||(G="/index"===(G=D)?"/":G);let H=!0===A.isDev||!F,I=F&&!H,J=a.method||"GET",K=(0,i.getTracer)(),L=K.getActiveScopeSpan(),M={params:v,prerenderManifest:y,renderOpts:{experimental:{cacheComponents:!!w.experimental.cacheComponents,authInterrupts:!!w.experimental.authInterrupts},supportsDynamicResponse:H,incrementalCache:(0,h.getRequestMeta)(a,"incrementalCache"),cacheLifeProfiles:null==(d=w.experimental)?void 0:d.cacheLife,isRevalidate:I,waitUntil:c.waitUntil,onClose:a=>{b.on("close",a)},onAfterTaskError:void 0,onInstrumentationRequestError:(b,c,d)=>A.onRequestError(a,b,d,z)},sharedContext:{buildId:u}},N=new k.NodeNextRequest(a),O=new k.NodeNextResponse(b),P=l.NextRequestAdapter.fromNodeNextRequest(N,(0,l.signalFromNodeResponse)(b));try{let d=async c=>A.handle(P,M).finally(()=>{if(!c)return;c.setAttributes({"http.status_code":b.statusCode,"next.rsc":!1});let d=K.getRootSpanAttributes();if(!d)return;if(d.get("next.span_type")!==m.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${d.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let e=d.get("next.route");if(e){let a=`${J} ${e}`;c.setAttributes({"next.route":e,"http.route":e,"next.span_name":a}),c.updateName(a)}else c.updateName(`${J} ${a.url}`)}),g=async g=>{var i,j;let k=async({previousCacheEntry:f})=>{try{if(!(0,h.getRequestMeta)(a,"minimalMode")&&B&&C&&!f)return b.statusCode=404,b.setHeader("x-nextjs-cache","REVALIDATED"),b.end("This page could not be found"),null;let e=await d(g);a.fetchMetrics=M.renderOpts.fetchMetrics;let i=M.renderOpts.pendingWaitUntil;i&&c.waitUntil&&(c.waitUntil(i),i=void 0);let j=M.renderOpts.collectedTags;if(!F)return await (0,o.I)(N,O,e,M.renderOpts.pendingWaitUntil),null;{let a=await e.blob(),b=(0,p.toNodeOutgoingHttpHeaders)(e.headers);j&&(b[r.NEXT_CACHE_TAGS_HEADER]=j),!b["content-type"]&&a.type&&(b["content-type"]=a.type);let c=void 0!==M.renderOpts.collectedRevalidate&&!(M.renderOpts.collectedRevalidate>=r.INFINITE_CACHE)&&M.renderOpts.collectedRevalidate,d=void 0===M.renderOpts.collectedExpire||M.renderOpts.collectedExpire>=r.INFINITE_CACHE?void 0:M.renderOpts.collectedExpire;return{value:{kind:t.CachedRouteKind.APP_ROUTE,status:e.status,body:Buffer.from(await a.arrayBuffer()),headers:b},cacheControl:{revalidate:c,expire:d}}}}catch(b){throw(null==f?void 0:f.isStale)&&await A.onRequestError(a,b,{routerKind:"App Router",routePath:e,routeType:"route",revalidateReason:(0,n.c)({isRevalidate:I,isOnDemandRevalidate:B})},z),b}},l=await A.handleResponse({req:a,nextConfig:w,cacheKey:G,routeKind:f.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:y,isRoutePPREnabled:!1,isOnDemandRevalidate:B,revalidateOnlyGenerated:C,responseGenerator:k,waitUntil:c.waitUntil});if(!F)return null;if((null==l||null==(i=l.value)?void 0:i.kind)!==t.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==l||null==(j=l.value)?void 0:j.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});(0,h.getRequestMeta)(a,"minimalMode")||b.setHeader("x-nextjs-cache",B?"REVALIDATED":l.isMiss?"MISS":l.isStale?"STALE":"HIT"),x&&b.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let m=(0,p.fromNodeOutgoingHttpHeaders)(l.value.headers);return(0,h.getRequestMeta)(a,"minimalMode")&&F||m.delete(r.NEXT_CACHE_TAGS_HEADER),!l.cacheControl||b.getHeader("Cache-Control")||m.get("Cache-Control")||m.set("Cache-Control",(0,q.getCacheControlHeader)(l.cacheControl)),await (0,o.I)(N,O,new Response(l.value.body,{headers:m,status:l.value.status||200})),null};L?await g(L):await K.withPropagatedContext(a.headers,()=>K.trace(m.BaseServerSpan.handleRequest,{spanName:`${J} ${a.url}`,kind:i.SpanKind.SERVER,attributes:{"http.method":J,"http.target":a.url}},g))}catch(b){if(b instanceof s.NoFallbackError||await A.onRequestError(a,b,{routerKind:"App Router",routePath:E,routeType:"route",revalidateReason:(0,n.c)({isRevalidate:I,isOnDemandRevalidate:B})}),F)throw b;return await (0,o.I)(N,O,new Response(null,{status:500})),null}}},529294:a=>{a.exports=require("next/dist/server/app-render/work-async-storage.external.js")},567472:(a,b,c)=>{c.d(b,{Ez:()=>l,Qw:()=>h,Ut:()=>m,cH:()=>n,fW:()=>k,gt:()=>j,x6:()=>i,y3:()=>g});var d=c(693349),e=c(612839);let f=null;async function g(a=!1){if(f&&!a)return f;let b=await (0,e.W3)(e.zq.people),c=await (0,e.W3)(e.zq.company),d=await (0,e.W3)(e.zq.email_thread),h=await (0,e.W3)(e.zq.email_message);return f={people:b,company:c,email_thread:d,email_message:h,calendar_event:await (0,e.W3)(e.zq.calendar_event),interaction:await (0,e.W3)(e.zq.interaction)}}function h(a){return`'${a.replace(/'/g,"''")}'`}function i(a,b){let c=b.replace(/'/g,"''").replace(/"/g,'""');return`${a} LIKE '%"${c}"%'`}function j(a){let b=a.objectId.replace(/'/g,"''"),c=a.aliasedFields.map(({name:b,alias:c})=>{let d=a.fieldMap[b];if(!d)return`NULL AS "${c}"`;let e=d.replace(/'/g,"''");return`MAX(CASE WHEN ef.field_id = '${e}' THEN ef.value END) AS "${c}"`}).join(",\n      "),d=a.whereSql?`AND ${a.whereSql}`:"",e=a.orderBySql?`ORDER BY ${a.orderBySql}`:"",f=void 0!==a.limit?`LIMIT ${Math.max(0,Math.floor(a.limit))}`:"";return`
    SELECT
      e.id AS entry_id,
      e.created_at,
      e.updated_at,
      ${c}
    FROM entries e
    LEFT JOIN entry_fields ef ON ef.entry_id = e.id
    WHERE e.object_id = '${b}'
      ${d}
    GROUP BY e.id, e.created_at, e.updated_at
    ${e}
    ${f}
  `}function k(a,b,c){let d=void 0!==c?`LIMIT ${Math.max(0,Math.floor(c))}`:"";return`
    SELECT * FROM (${a}) sub
    ${b?`ORDER BY ${b}`:""}
    ${d}
  `}async function l(a,b=[]){try{return await (0,d.AI)(a)}catch{return b}}function m(a){let b=a.emailMessageFieldMap,c=b.Thread,d=b["Sent At"];if(!c||!d)return null;let f=b["Sender Type"],g=b["Body Preview"],h=b.From,i=[c,d];f&&i.push(f),g&&i.push(g),h&&i.push(h);let j=i.map(a=>`'${a.replace(/'/g,"''")}'`).join(", "),k=a.candidateThreadIdsCte?`WHERE m.thread_value IN (SELECT entry_id FROM ${a.candidateThreadIdsCte})`:"WHERE m.thread_value IS NOT NULL";return{cte:`
    latest_msg AS (
      SELECT
        thread_value AS thread_id,
        ${f?"ARG_MAX(sender_type_value, sent_at_value)":"NULL"} AS sender_type,
        ${g?"ARG_MAX(preview_value, sent_at_value)":"NULL"} AS snippet,
        ${h?"ARG_MAX(from_value, sent_at_value)":"NULL"} AS from_person_id
      FROM (
        SELECT
          e.id AS msg_id,
          MAX(CASE WHEN ef.field_id = '${c}' THEN ef.value END) AS thread_value,
          MAX(CASE WHEN ef.field_id = '${d}' THEN ef.value END) AS sent_at_value,
          ${f?`MAX(CASE WHEN ef.field_id = '${f}' THEN ef.value END)`:"NULL"} AS sender_type_value,
          ${g?`MAX(CASE WHEN ef.field_id = '${g}' THEN ef.value END)`:"NULL"} AS preview_value,
          ${h?`MAX(CASE WHEN ef.field_id = '${h}' THEN ef.value END)`:"NULL"} AS from_value
        FROM entries e
        JOIN entry_fields ef
          ON ef.entry_id = e.id
         AND ef.field_id IN (${j})
        WHERE e.object_id = '${e.zq.email_message}'
        GROUP BY e.id
      ) m
      ${k}
      GROUP BY thread_value
    )
  `,joinClause:"LEFT JOIN latest_msg ON latest_msg.thread_id = base.entry_id"}}async function n(a,b){let c=new Map;if(0===a.length)return c;let d=b["Full Name"],f=b["Email Address"],g=b["Avatar URL"];if(!d&&!f)return c;let h=a.map(a=>`'${a.replace(/'/g,"''")}'`).join(", "),i=`
    SELECT
      e.id AS person_id,
      ${d?`MAX(CASE WHEN ef.field_id = '${d}' THEN ef.value END)`:"NULL"} AS name,
      ${f?`MAX(CASE WHEN ef.field_id = '${f}' THEN ef.value END)`:"NULL"} AS email,
      ${g?`MAX(CASE WHEN ef.field_id = '${g}' THEN ef.value END)`:"NULL"} AS avatar_url
    FROM entries e
    LEFT JOIN entry_fields ef ON ef.entry_id = e.id
    WHERE e.object_id = '${e.zq.people}'
      AND e.id IN (${h})
    GROUP BY e.id;
  `;for(let a of(await l(i)))c.set(a.person_id,{id:a.person_id,name:a.name,email:a.email,avatar_url:a.avatar_url});return c}},663033:a=>{a.exports=require("next/dist/server/app-render/work-unit-async-storage.external.js")},710846:a=>{a.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},719771:a=>{a.exports=require("process")},731421:a=>{a.exports=require("node:child_process")},744870:a=>{a.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},848161:a=>{a.exports=require("node:os")},940527:(a,b,c)=>{a.exports=c(744870)},973024:a=>{a.exports=require("node:fs")},979428:a=>{a.exports=require("buffer")},986439:a=>{a.exports=require("next/dist/shared/lib/no-fallback-error.external")}};var b=require("../../../../webpack-runtime.js");b.C(a);var c=b.X(0,[76973,22137,93349,66131],()=>b(b.s=321947));module.exports=c})();