import { NextRequest, NextResponse } from 'next/server'; import { requireAdminAuth, createUnauthorizedResponse, createForbiddenResponse } from './index'; export type AdminAuth = { userId: string; username: string; sessionRole: 'admin'; }; /** * Wrapper for admin API routes without dynamic params * Handles authentication and error responses automatically * * Usage: * export const GET = withAdminAuth(async (request, auth) => { * // auth is guaranteed to be valid admin * return NextResponse.json({ data }); * }); */ export function withAdminAuth( handler: (request: NextRequest, auth: AdminAuth) => Promise ): (request: NextRequest) => Promise { return async (request: NextRequest): Promise => { try { const auth = await requireAdminAuth(request); return handler(request, auth); } catch (error) { if (error instanceof Error) { if (error.message === 'Unauthorized') { return createUnauthorizedResponse(); } if (error.message === 'Forbidden') { return createForbiddenResponse(); } } console.error('[Admin Route Handler] Unexpected error:', error); return NextResponse.json({ error: 'Internal server error' }, { status: 500 }); } }; } /** * Wrapper for admin API routes WITH dynamic params (e.g., [conversationId]) * Handles authentication and error responses automatically * * Usage: * export const GET = withAdminAuthParams<{ conversationId: string }>( * async (request, auth, { params }) => { * const { conversationId } = await params; * return NextResponse.json({ data }); * } * ); */ export function withAdminAuthParams( handler: ( request: NextRequest, auth: AdminAuth, context: { params: Promise } ) => Promise ): (request: NextRequest, context: { params: Promise }) => Promise { return async ( request: NextRequest, context: { params: Promise } ): Promise => { try { const auth = await requireAdminAuth(request); return handler(request, auth, context); } catch (error) { if (error instanceof Error) { if (error.message === 'Unauthorized') { return createUnauthorizedResponse(); } if (error.message === 'Forbidden') { return createForbiddenResponse(); } } console.error('[Admin Route Handler] Unexpected error:', error); return NextResponse.json({ error: 'Internal server error' }, { status: 500 }); } }; }