import createMiddleware from 'next-intl/middleware';
import { NextRequest } from 'next/server';
import { routing } from './i18n/routing';

const intlMiddleware = createMiddleware(routing);

export default function middleware(request: NextRequest) {
  const response = intlMiddleware(request);

  // For non-redirect responses, forward the pathname as a request header so
  // generateMetadata in [locale]/layout.tsx can build self-referencing
  // canonical URLs and per-page hreflang tags server-side.
  //
  // Next.js reads any response header prefixed with "x-middleware-request-"
  // and forwards it (without the prefix) as a request header to the app.
  // This is the documented way to pass middleware data to Server Components
  // via headers() without replacing next-intl's response (and losing its
  // internal URL rewrites that make localePrefix: 'as-needed' work).
  if (response.status < 300 || response.status >= 400) {
    response.headers.set(
      'x-middleware-request-x-pathname',
      request.nextUrl.pathname
    );
  }

  return response;
}

export const config = {
  // Match all paths except Next.js internals, static files, API routes, and OG image
  matcher: ['/((?!api|_next|_vercel|opengraph-image|.*\\..*).*)'],
};
