import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { verifyAuth } from './lib/auth';

// Simple in-memory rate limiter
const rateLimitMap = new Map();

export async function proxy(req: NextRequest) {
  const response = NextResponse.next();

  // --- Security Headers ---
  const headers = response.headers;
  headers.set('X-Frame-Options', 'DENY');
  headers.set('X-Content-Type-Options', 'nosniff');
  headers.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
  headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
  headers.set('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');

  // --- Rate Limiting for API routes ---
  if (req.nextUrl.pathname.startsWith('/api/')) {
    const ip = req.headers.get('x-forwarded-for') || 'ip';
    const limit = 100; // 100 requests per minute
    const windowMs = 60 * 1000;

    if (!rateLimitMap.has(ip)) {
      rateLimitMap.set(ip, { count: 0, lastReset: Date.now() });
    }

    const ipData = rateLimitMap.get(ip);

    if (Date.now() - ipData.lastReset > windowMs) {
      ipData.count = 0;
      ipData.lastReset = Date.now();
    }

    ipData.count += 1;

    if (ipData.count > limit) {
      return new NextResponse('Too Many Requests', { status: 429 });
    }
  }

  // --- Admin Route Protection ---
  if (req.nextUrl.pathname.startsWith('/admin')) {
    // Allow login page
    if (req.nextUrl.pathname === '/admin/login') {
      return response;
    }

    const token = req.cookies.get('auth_token')?.value;

    const verifiedToken = token && (await verifyAuth(token).catch((err) => {
      console.error(err.message);
    }));

    if (!verifiedToken) {
      return NextResponse.redirect(new URL('/admin/login', req.url));
    }
  }

  return response;
}

export const config = {
  matcher: [
    '/((?!_next/static|_next/image|favicon.ico).*)',
  ],
};
