module.exports=[48742,e=>{"use strict";var t=e.i(747909),r=e.i(174017),a=e.i(996250),n=e.i(759756),s=e.i(561916),i=e.i(174677),o=e.i(869741),l=e.i(316795),d=e.i(487718),u=e.i(995169),c=e.i(47587),p=e.i(666012),f=e.i(570101),h=e.i(626937),m=e.i(10372),R=e.i(193695);e.i(52474);var E=e.i(600220),b=e.i(89171);e.i(236532);var w=e.i(557161),_=e.i(679371);e.i(484848);var v=e.i(526571),g=e.i(284640),N=e.i(348189),A=e.i(875225),C=e.i(349129),T=e.i(518899);async function I(e){try{let t,r=await (0,w.getUserFromRequest)(e);if(!r?.id)return b.NextResponse.json({success:!1,error:"Unauthorized"},{status:401});if("super_admin"!==r.role&&"admin"!==r.role)return b.NextResponse.json({success:!1,error:"Forbidden - Admin access required"},{status:403});let{searchParams:a}=new URL(e.url),n=a.get("period")||"all",s=parseInt(a.get("limit")||"10");"week"===n?t=new Date(Date.now()-6048e5):"month"===n&&(t=new Date(Date.now()-2592e6));let[i,o,l,d]=await Promise.all([_.db.select({referrerId:T.sql`COALESCE(${v.users.referred_by}, 0)`.as("referrer_id"),referredUserId:v.users.id,referredUserName:v.users.name}).from(v.users).where(T.sql`${v.users.referred_by} IS NOT NULL`),_.db.execute(T.sql`
        SELECT
          u.referred_by as referrer_id,
          COUNT(*) as total_applications,
          COUNT(*) FILTER (WHERE ba.fee = 0 OR ba.is_45_days_free = true) as free_applications,
          COUNT(*) FILTER (WHERE ba.fee > 0 AND ba.is_45_days_free = false) as paid_applications
        FROM ${g.bdrisApplications} ba
        INNER JOIN ${v.users} u ON ba.user_id = u.id
        WHERE u.referred_by IS NOT NULL
          ${t?T.sql`AND ba.submitted_at >= ${t.toISOString()}`:T.sql``}
        GROUP BY u.referred_by
      `),_.db.execute(T.sql`
        SELECT
          user_id as referrer_id,
          COALESCE(SUM(amount), 0) as total_income
        FROM ${N.balanceTransactions}
        WHERE reason = 'referral'
          ${t?T.sql`AND created_at >= ${t.toISOString()}`:T.sql``}
        GROUP BY user_id
      `),_.db.select({userId:N.balanceTransactions.userId,amount:N.balanceTransactions.amount,referenceId:N.balanceTransactions.referenceId,description:N.balanceTransactions.description,createdAt:N.balanceTransactions.created_at,userName:v.users.name,userPhone:v.users.phone}).from(N.balanceTransactions).innerJoin(v.users,(0,A.eq)(N.balanceTransactions.userId,v.users.id)).where(T.sql`${N.balanceTransactions.reason} = ${"referral"}`).orderBy((0,C.desc)(N.balanceTransactions.created_at)).limit(20)]),u=[...new Set([...i.map(e=>e.referrerId),...l.map(e=>e.referrer_id)])].filter(e=>e>0),c=u.length>0?await _.db.select({id:v.users.id,name:v.users.name,phone:v.users.phone,balance:v.users.balance,role:v.users.role}).from(v.users).where((0,A.inArray)(v.users.id,u)):[],p=new Map(c.map(e=>[e.id,{name:e.name,phone:e.phone,balance:e.balance,role:e.role}])),f=new Map(l.map(e=>[e.referrer_id,Number(e.total_income)])),h=new Map(o.map(e=>[e.referrer_id,{total:Number(e.total_applications),free:Number(e.free_applications),paid:Number(e.paid_applications)}])),m=new Map;for(let e of i){let t=e.referrerId;t&&m.set(t,(m.get(t)||0)+1)}let R=u.map(e=>{let t=p.get(e),r=h.get(e),a=f.get(e)||0,n=m.get(e)||0;return t?{referrerId:e,referrerName:t.name,referrerPhone:t.phone,referrerBalance:t.balance,referrerRole:t.role,totalUsersReferred:n,totalApplications:r?.total||0,freeApplications:r?.free||0,paidApplications:r?.paid||0,totalIncome:a}:null}).filter(e=>null!==e),E=[...R].sort((e,t)=>t.totalIncome-e.totalIncome),I=[...R].sort((e,t)=>t.totalApplications-e.totalApplications),y=R.length,x=R.reduce((e,t)=>e+t.totalApplications,0),O=R.reduce((e,t)=>e+t.totalIncome,0),S=R.reduce((e,t)=>e+t.freeApplications,0),P=R.reduce((e,t)=>e+t.totalUsersReferred,0);return b.NextResponse.json({success:!0,data:{summary:{totalReferrers:y,totalUsersReferred:P,totalApplications:x,totalIncome:O,totalFreeApplications:S,totalPaidApplications:x-S,avgIncomePerReferrer:y>0?Math.round(O/y):0,avgApplicationsPerReferrer:y>0?Math.round(x/y):0},topEarners:E.slice(0,s),topReferrers:I.slice(0,s),allReferrers:I,recentRewards:d.map(e=>({userId:e.userId,amount:e.amount,referenceId:e.referenceId,description:e.description,createdAt:e.createdAt,userName:e.userName,userPhone:e.userPhone}))}})}catch(e){return console.error("[Referral Stats] Error:",e),b.NextResponse.json({success:!1,error:"Failed to fetch referral statistics"},{status:500})}}e.s(["GET",0,I],338206);var y=e.i(338206);let x=new t.AppRouteRouteModule({definition:{kind:r.RouteKind.APP_ROUTE,page:"/api/admin/referral-stats/route",pathname:"/api/admin/referral-stats",filename:"route",bundlePath:""},distDir:"_next",relativeProjectDir:"",resolvedPagePath:"[project]/src/app/api/admin/referral-stats/route.ts",nextConfigOutput:"standalone",userland:y,...{}}),{workAsyncStorage:O,workUnitAsyncStorage:S,serverHooks:P}=x;async function U(e,t,a){a.requestMeta&&(0,n.setRequestMeta)(e,a.requestMeta),x.isDev&&(0,n.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let b="/api/admin/referral-stats/route";b=b.replace(/\/index$/,"")||"/";let w=await x.prepare(e,t,{srcPage:b,multiZoneDraftMode:!1});if(!w)return t.statusCode=400,t.end("Bad Request"),null==a.waitUntil||a.waitUntil.call(a,Promise.resolve()),null;let{buildId:_,params:v,nextConfig:g,parsedUrl:N,isDraftMode:A,prerenderManifest:C,routerServerContext:T,isOnDemandRevalidate:I,revalidateOnlyGenerated:y,resolvedPathname:O,clientReferenceManifest:S,serverActionsManifest:P}=w,U=(0,o.normalizeAppPath)(b),q=!!(C.dynamicRoutes[U]||C.routes[O]),M=async()=>((null==T?void 0:T.render404)?await T.render404(e,t,N,!1):t.end("This page could not be found"),null);if(q&&!A){let e=!!C.routes[O],t=C.dynamicRoutes[U];if(t&&!1===t.fallback&&!e){if(g.adapterPath)return await M();throw new R.NoFallbackError}}let H=null;!q||x.isDev||A||(H="/index"===(H=O)?"/":H);let D=!0===x.isDev||!q,$=q&&!D;P&&S&&(0,i.setManifestsSingleton)({page:b,clientReferenceManifest:S,serverActionsManifest:P});let L=e.method||"GET",F=(0,s.getTracer)(),k=F.getActiveScopeSpan(),j=!!(null==T?void 0:T.isWrappedByNextServer),B=!!(0,n.getRequestMeta)(e,"minimalMode"),K=(0,n.getRequestMeta)(e,"incrementalCache")||await x.getIncrementalCache(e,g,C,B);null==K||K.resetRequestCache(),globalThis.__incrementalCache=K;let W={params:v,previewProps:C.preview,renderOpts:{experimental:{authInterrupts:!!g.experimental.authInterrupts},cacheComponents:!!g.cacheComponents,supportsDynamicResponse:D,incrementalCache:K,cacheLifeProfiles:g.cacheLife,waitUntil:a.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,r,a,n)=>x.onRequestError(e,t,a,n,T)},sharedContext:{buildId:_}},G=new l.NodeNextRequest(e),V=new l.NodeNextResponse(t),X=d.NextRequestAdapter.fromNodeNextRequest(G,(0,d.signalFromNodeResponse)(t));try{let n,i=async e=>x.handle(X,W).finally(()=>{if(!e)return;e.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let r=F.getRootSpanAttributes();if(!r)return;if(r.get("next.span_type")!==u.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${r.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let a=r.get("next.route");if(a){let t=`${L} ${a}`;e.setAttributes({"next.route":a,"http.route":a,"next.span_name":t}),e.updateName(t),n&&n!==e&&(n.setAttribute("http.route",a),n.updateName(t))}else e.updateName(`${L} ${b}`)}),o=async n=>{var s,o;let l=async({previousCacheEntry:r})=>{try{if(!B&&I&&y&&!r)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let s=await i(n);e.fetchMetrics=W.renderOpts.fetchMetrics;let o=W.renderOpts.pendingWaitUntil;o&&a.waitUntil&&(a.waitUntil(o),o=void 0);let l=W.renderOpts.collectedTags;if(!q)return await (0,p.sendResponse)(G,V,s,W.renderOpts.pendingWaitUntil),null;{let e=await s.blob(),t=(0,f.toNodeOutgoingHttpHeaders)(s.headers);l&&(t[m.NEXT_CACHE_TAGS_HEADER]=l),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let r=void 0!==W.renderOpts.collectedRevalidate&&!(W.renderOpts.collectedRevalidate>=m.INFINITE_CACHE)&&W.renderOpts.collectedRevalidate,a=void 0===W.renderOpts.collectedExpire||W.renderOpts.collectedExpire>=m.INFINITE_CACHE?void 0:W.renderOpts.collectedExpire;return{value:{kind:E.CachedRouteKind.APP_ROUTE,status:s.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:r,expire:a}}}}catch(t){throw(null==r?void 0:r.isStale)&&await x.onRequestError(e,t,{routerKind:"App Router",routePath:b,routeType:"route",revalidateReason:(0,c.getRevalidateReason)({isStaticGeneration:$,isOnDemandRevalidate:I})},!1,T),t}},d=await x.handleResponse({req:e,nextConfig:g,cacheKey:H,routeKind:r.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:C,isRoutePPREnabled:!1,isOnDemandRevalidate:I,revalidateOnlyGenerated:y,responseGenerator:l,waitUntil:a.waitUntil,isMinimalMode:B});if(!q)return null;if((null==d||null==(s=d.value)?void 0:s.kind)!==E.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==d||null==(o=d.value)?void 0:o.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});B||t.setHeader("x-nextjs-cache",I?"REVALIDATED":d.isMiss?"MISS":d.isStale?"STALE":"HIT"),A&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let u=(0,f.fromNodeOutgoingHttpHeaders)(d.value.headers);return B&&q||u.delete(m.NEXT_CACHE_TAGS_HEADER),!d.cacheControl||t.getHeader("Cache-Control")||u.get("Cache-Control")||u.set("Cache-Control",(0,h.getCacheControlHeader)(d.cacheControl)),await (0,p.sendResponse)(G,V,new Response(d.value.body,{headers:u,status:d.value.status||200})),null};j&&k?await o(k):(n=F.getActiveScopeSpan(),await F.withPropagatedContext(e.headers,()=>F.trace(u.BaseServerSpan.handleRequest,{spanName:`${L} ${b}`,kind:s.SpanKind.SERVER,attributes:{"http.method":L,"http.target":e.url}},o),void 0,!j))}catch(t){if(t instanceof R.NoFallbackError||await x.onRequestError(e,t,{routerKind:"App Router",routePath:U,routeType:"route",revalidateReason:(0,c.getRevalidateReason)({isStaticGeneration:$,isOnDemandRevalidate:I})},!1,T),q)throw t;return await (0,p.sendResponse)(G,V,new Response(null,{status:500})),null}}e.s(["handler",0,U,"patchFetch",0,function(){return(0,a.patchFetch)({workAsyncStorage:O,workUnitAsyncStorage:S})},"routeModule",0,x,"serverHooks",0,P,"workAsyncStorage",0,O,"workUnitAsyncStorage",0,S],48742)}];

//# sourceMappingURL=node_modules_next_dist_esm_build_templates_app-route_13p60a1.js.map