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

const allowedOrigins = [
  'https://wolna-glowa.pl',
  'http://localhost:3000',
  'http://localhost:3001',
];

const RATE_LIMIT = 60; // requests per minute
const ipCache = new Map();

export function middleware(request: NextRequest) {
  // Only apply to API routes
  if (!request.nextUrl.pathname.startsWith('/api/')) {
    return NextResponse.next();
  }

  const origin = request.headers.get('origin');
  if (origin && !allowedOrigins.includes(origin)) {
    return new NextResponse('CORS Not Allowed', { status: 403 });
  }

  // Basic rate limiting by IP
  const ip = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() || 'unknown';
  const now = Date.now();
  const windowStart = now - 60 * 1000;
  let requests = ipCache.get(ip) || [];
  requests = requests.filter((timestamp: number) => timestamp > windowStart);
  if (requests.length >= RATE_LIMIT) {
    return new NextResponse('Rate limit exceeded', { status: 429 });
  }
  requests.push(now);
  ipCache.set(ip, requests);

  return NextResponse.next();
}

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