import { createI18nMiddleware } from 'next-international/middleware'
import { NextRequest, NextResponse } from 'next/server'

const I18nMiddleware = createI18nMiddleware({
  locales: ['en', 'ru', 'es'],
  defaultLocale: 'en',
})

export function middleware(request: NextRequest) {
  const response = I18nMiddleware(request)
  response.headers.set('x-url', request.url)

  // If the response is a redirect (status 307), convert it to 301
  if (response.status === 307) {
    const redirectUrl = response.headers.get('Location')
    if (redirectUrl) {
      return NextResponse.redirect(redirectUrl, 301)
    }
  }

  return response
}

export const config = {
  matcher: ['/((?!api|static|.*\\..*|_next|favicon.ico|robots.txt|admin).*)'],
}
