import {
  defaultLocale,
  isLocale,
  localeCookie,
  localeCookieMaxAgeSeconds,
  localeFromAcceptLanguage,
} from '@/lib/localization/config';
import { buildContentSecurityPolicy, createNonce } from '@/lib/security/csp';
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';

function applySecurityHeaders(response: NextResponse, contentSecurityPolicy: string): NextResponse {
  response.headers.set('Content-Security-Policy', contentSecurityPolicy);
  response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
  response.headers.set('X-Content-Type-Options', 'nosniff');
  response.headers.set('X-Frame-Options', 'DENY');
  response.headers.set('Cross-Origin-Opener-Policy', 'same-origin');
  response.headers.set('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
  return response;
}

export function proxy(request: NextRequest): NextResponse {
  const nonce = createNonce();
  const csp = buildContentSecurityPolicy(nonce, process.env.NODE_ENV !== 'production');
  const requestHeaders = new Headers(request.headers);
  requestHeaders.set('x-nonce', nonce);
  requestHeaders.set('Content-Security-Policy', csp);

  if (request.nextUrl.pathname === '/') {
    const cookieLocale = request.cookies.get(localeCookie)?.value;
    const locale = isLocale(cookieLocale)
      ? cookieLocale
      : localeFromAcceptLanguage(request.headers.get('accept-language')) || defaultLocale;
    const destination = request.nextUrl.clone();
    destination.pathname = `/${locale}`;
    const response = NextResponse.redirect(destination);
    response.cookies.set(localeCookie, locale, {
      path: '/',
      sameSite: 'lax',
      maxAge: localeCookieMaxAgeSeconds,
      secure: process.env.NODE_ENV === 'production',
      httpOnly: false,
    });
    return applySecurityHeaders(response, csp);
  }

  const response = NextResponse.next({ request: { headers: requestHeaders } });
  const explicitLocale = request.nextUrl.pathname.split('/')[1];
  if (isLocale(explicitLocale)) {
    response.cookies.set(localeCookie, explicitLocale, {
      path: '/',
      sameSite: 'lax',
      maxAge: localeCookieMaxAgeSeconds,
      secure: process.env.NODE_ENV === 'production',
      httpOnly: false,
    });
  }
  return applySecurityHeaders(response, csp);
}

export const config = {
  matcher: [
    {
      source: '/((?!api|_next/static|_next/image|assets|favicon.ico|robots.txt|sitemap.xml).*)',
      missing: [
        { type: 'header', key: 'next-router-prefetch' },
        { type: 'header', key: 'purpose', value: 'prefetch' },
      ],
    },
  ],
};
