import { type NextRequest, NextResponse } from 'next/server'

// Arabic is the site's default language and lives at the root ("/courses"); English lives under "/en".
// Internally every page sits under /[locale]/…, so a root address is rewritten to /ar/….
export function proxy(req: NextRequest) {
  const { pathname, search } = req.nextUrl
  if (pathname === '/en' || pathname.startsWith('/en/')) return NextResponse.next()
  // one address per page: /ar/… is the same page as /…
  if (pathname === '/ar' || pathname.startsWith('/ar/')) {
    const url = req.nextUrl.clone()
    url.pathname = pathname.slice(3) || '/'
    return NextResponse.redirect(url, 308)
  }
  const url = req.nextUrl.clone()
  url.pathname = `/ar${pathname === '/' ? '' : pathname}`
  url.search = search
  return NextResponse.rewrite(url)
}

export const config = {
  // everything except the CMS, its API, Next's own files and static files (anything with a dot, but the old .html pages)
  matcher: ['/((?!admin|api|_next|brand/|assets/|favicon|robots\\.txt|sitemap\\.xml|.*\\.(?!html$)[a-z0-9]+$).*)'],
}
