(()=>{var a={};a.id=4376,a.ids=[4376],a.modules={261:a=>{"use strict";a.exports=require("next/dist/shared/lib/router/utils/app-paths")},3295:a=>{"use strict";a.exports=require("next/dist/server/app-render/after-task-async-storage.external.js")},10846:a=>{"use strict";a.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},19121:a=>{"use strict";a.exports=require("next/dist/server/app-render/action-async-storage.external.js")},22029:(a,b,c)=>{"use strict";c.d(b,{aJ:()=>d});let d=a=>/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(a)},25224:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{A:()=>g});var e=c(64939),f=a([e]);let g=new(e=(f.then?(await f)():f)[0]).Pool({user:process.env.DB_USER,host:process.env.DB_HOST,database:process.env.DB_NAME,password:process.env.DB_PASSWORD,port:parseInt(process.env.DB_PORT||"5432")});d()}catch(a){d(a)}})},29021:a=>{"use strict";a.exports=require("fs")},29294:a=>{"use strict";a.exports=require("next/dist/server/app-render/work-async-storage.external.js")},33873:a=>{"use strict";a.exports=require("path")},44870:a=>{"use strict";a.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},50283:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.r(b),c.d(b,{GET:()=>o,POST:()=>p,PUT:()=>q});var e=c(10641),f=c(25224),g=c(22029),h=c(79748),i=c(33873),j=c.n(i),k=c(29021),l=a([f]);f=(l.then?(await l)():l)[0];let r=j().join(process.cwd(),"public/uploads/party-logos");async function m(a){(0,k.existsSync)(r)||await (0,h.mkdir)(r,{recursive:!0});let b=Date.now(),c=Math.round(1e9*Math.random()),d=a.name.split(".").pop(),e=`party-logo-${b}-${c}.${d}`,f=j().join(r,e),g=await a.arrayBuffer(),i=Buffer.from(g);return await (0,h.writeFile)(f,i),`/uploads/party-logos/${e}`}async function n(a){if(a)try{let b=j().join(process.cwd(),"public",a);(0,k.existsSync)(b)&&await (0,h.unlink)(b)}catch(a){console.error("Error deleting old logo:",a)}}async function o(a){let{searchParams:b}=new URL(a.url),c=b.get("search")||"",d="true"===b.get("all"),g=d?1:parseInt(b.get("page")||"1"),h=d?null:parseInt(b.get("limit")||"50"),i=d?0:(g-1)*(h||50);try{let a=`
      SELECT 
        id,
        name,
        abbreviation,
        logo_path,
        created_at,
        updated_at
      FROM political_parties
      WHERE 1=1
    `,b=[],j=0;c&&(j++,a+=` AND (
        name ILIKE $${j} OR 
        abbreviation ILIKE $${j}
      )`,b.push(`%${c}%`)),a+=" ORDER BY name";let k=`SELECT COUNT(*) FROM (${a}) as count_query`,l=await f.A.query(k,b),m=parseInt(l.rows[0].count);!d&&h&&(a+=` LIMIT $${j+1} OFFSET $${j+2}`,b.push(h,i));let n={parties:(await f.A.query(a,b)).rows};return!d&&h?n.pagination={page:g,limit:h,totalCount:m,totalPages:Math.ceil(m/h)}:n.pagination={totalCount:m},e.NextResponse.json(n)}catch(a){return console.error("Error fetching political parties:",a),e.NextResponse.json({error:"Internal server error"},{status:500})}}async function p(a){try{let b=await a.formData(),c=b.get("name"),d=b.get("abbreviation"),h=b.get("id")||null,i=b.get("logo");if(!c||!d)return e.NextResponse.json({error:"Name and abbreviation are required"},{status:400});if(h&&!(0,g.aJ)(h))return e.NextResponse.json({error:"Invalid UUID format"},{status:400});let j=null;if(i&&i.size>0){if(!i.type.startsWith("image/"))return e.NextResponse.json({error:"Only image files are allowed"},{status:400});if(i.size>5242880)return e.NextResponse.json({error:"File size must be less than 5MB"},{status:400});j=await m(i)}let k=`
      INSERT INTO political_parties (
        id, name, abbreviation, logo_path
      )
      VALUES ($1, $2, $3, $4)
      RETURNING *
    `,l=[h||null,c.trim(),d.trim().toUpperCase(),j],n=await f.A.query(k,l);return e.NextResponse.json(n.rows[0])}catch(a){return console.error("Error creating political party:",a),e.NextResponse.json({error:"Internal server error"},{status:500})}}async function q(a){try{let b=await a.formData(),c=b.get("id"),d=b.get("name"),h=b.get("abbreviation"),i=b.get("logo");if(!c)return e.NextResponse.json({error:"Party ID is required for update"},{status:400});if(!(0,g.aJ)(c))return e.NextResponse.json({error:"Invalid UUID format"},{status:400});if(!d||!h)return e.NextResponse.json({error:"Name and abbreviation are required"},{status:400});let j=await f.A.query("SELECT logo_path FROM political_parties WHERE id = $1",[c]);if(0===j.rows.length)return e.NextResponse.json({error:"Political party not found"},{status:404});let k=j.rows[0].logo_path,l=k;if(i&&i.size>0){if(!i.type.startsWith("image/"))return e.NextResponse.json({error:"Only image files are allowed"},{status:400});if(i.size>5242880)return e.NextResponse.json({error:"File size must be less than 5MB"},{status:400});k&&await n(k),l=await m(i)}let o=`
      UPDATE political_parties 
      SET 
        name = $1,
        abbreviation = $2,
        logo_path = $3,
        updated_at = CURRENT_TIMESTAMP
      WHERE id = $4
      RETURNING *
    `,p=[d.trim(),h.trim().toUpperCase(),l,c],q=await f.A.query(o,p);if(0===q.rows.length)return e.NextResponse.json({error:"Political party not found"},{status:404});return e.NextResponse.json(q.rows[0])}catch(a){return console.error("Error updating political party:",a),e.NextResponse.json({error:"Internal server error"},{status:500})}}d()}catch(a){d(a)}})},63033:a=>{"use strict";a.exports=require("next/dist/server/app-render/work-unit-async-storage.external.js")},64939:a=>{"use strict";a.exports=import("pg")},74374:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.r(b),c.d(b,{handler:()=>x,patchFetch:()=>w,routeModule:()=>y,serverHooks:()=>B,workAsyncStorage:()=>z,workUnitAsyncStorage:()=>A});var e=c(95736),f=c(9117),g=c(4044),h=c(39326),i=c(32324),j=c(261),k=c(54290),l=c(85328),m=c(38928),n=c(46595),o=c(3421),p=c(17679),q=c(41681),r=c(63446),s=c(86439),t=c(51356),u=c(50283),v=a([u]);u=(v.then?(await v)():v)[0];let y=new e.AppRouteRouteModule({definition:{kind:f.RouteKind.APP_ROUTE,page:"/api/political-parties/route",pathname:"/api/political-parties",filename:"route",bundlePath:"app/api/political-parties/route"},distDir:".next",relativeProjectDir:"",resolvedPagePath:"/Users/kanyinsola/Documents/koh/kohfrontline/src/app/api/political-parties/route.ts",nextConfigOutput:"standalone",userland:u}),{workAsyncStorage:z,workUnitAsyncStorage:A,serverHooks:B}=y;function w(){return(0,g.patchFetch)({workAsyncStorage:z,workUnitAsyncStorage:A})}async function x(a,b,c){var d;let e="/api/political-parties/route";"/index"===e&&(e="/");let g=await y.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:z,routerServerContext:A,isOnDemandRevalidate:B,revalidateOnlyGenerated:C,resolvedPathname:D}=g,E=(0,j.normalizeAppPath)(e),F=!!(z.dynamicRoutes[E]||z.routes[D]);if(F&&!x){let a=!!z.routes[D],b=z.dynamicRoutes[E];if(b&&!1===b.fallback&&!a)throw new s.NoFallbackError}let G=null;!F||y.isDev||x||(G=D,G="/index"===G?"/":G);let H=!0===y.isDev||!F,I=F&&!H,J=a.method||"GET",K=(0,i.getTracer)(),L=K.getActiveScopeSpan(),M={params:v,prerenderManifest:z,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)=>y.onRequestError(a,b,d,A)},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=>y.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 y.onRequestError(a,b,{routerKind:"App Router",routePath:e,routeType:"route",revalidateReason:(0,n.c)({isRevalidate:I,isOnDemandRevalidate:B})},A),b}},l=await y.handleResponse({req:a,nextConfig:w,cacheKey:G,routeKind:f.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:z,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(L||b instanceof s.NoFallbackError||await y.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}}d()}catch(a){d(a)}})},78335:()=>{},79748:a=>{"use strict";a.exports=require("fs/promises")},86439:a=>{"use strict";a.exports=require("next/dist/shared/lib/no-fallback-error.external")},96487:()=>{}};var b=require("../../../webpack-runtime.js");b.C(a);var c=b.X(0,[4586,1692],()=>b(b.s=74374));module.exports=c})();