import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export async function middleware(request: NextRequest): Promise<NextResponse | undefined> {
  try {
    const apiKey = request.headers.get('x-api-key');

    if (!apiKey || apiKey !== process.env.API_KEY) {
      return NextResponse.json({ message: 'Invalid API key' }, { status: 401 });
    }

    // If the API key is valid, we don't return anything, allowing the request to proceed
    return undefined;
  } catch (error) {
    console.error('Middleware error:', error);
    return NextResponse.json({ message: 'Internal server error' }, { status: 500 });
  }
}

export const config = {
  matcher: '/api/:path*',
};
