import { NextRequest, NextResponse } from 'next/server';
import createMiddleware from 'next-intl/middleware';
import { locales, defaultLocale } from './i18n/config';
import { randomBytes } from 'crypto';

const CSRF_TOKEN_COOKIE_NAME = 'csrf_token';
const CSRF_TOKEN_LENGTH = 32;

const intlMiddleware = createMiddleware({
  locales,
  defaultLocale,
  localePrefix: 'always',
});

export default function middleware(request: NextRequest) {
  // Run the i18n middleware first
  const response = intlMiddleware(request);

  // Check if CSRF token exists in cookies
  const existingToken = request.cookies.get(CSRF_TOKEN_COOKIE_NAME);

  // Generate and set CSRF token if it doesn't exist
  if (!existingToken) {
    const newToken = randomBytes(CSRF_TOKEN_LENGTH).toString('base64url');

    // Create a new response or clone the existing one
    const finalResponse = response || NextResponse.next();

    finalResponse.cookies.set(CSRF_TOKEN_COOKIE_NAME, newToken, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'strict',
      maxAge: 60 * 60 * 24, // 24 hours
      path: '/',
    });

    return finalResponse;
  }

  return response;
}

export const config = {
  matcher: [
    '/',
    '/(de|en|sr)/:path*',
    '/((?!api|_next|_vercel|.*\\..*).*)',
  ],
};
