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

const SHARED_LANGUAGE_COOKIE = 'rentaldrivego-language'

type Language = 'en' | 'fr' | 'ar'

function isValidLanguage(value: string | null | undefined): value is Language {
  return value === 'en' || value === 'fr' || value === 'ar'
}

function detectFromAcceptLanguage(header: string | null): Language {
  if (!header) return 'en'
  for (const entry of header.split(',')) {
    const code = entry.split(';')[0].trim().split('-')[0].toLowerCase()
    if (isValidLanguage(code)) return code
  }
  return 'en'
}

export function proxy(request: NextRequest) {
  if (request.headers.has('x-middleware-subrequest')) {
    return new NextResponse('Unsupported internal request header', { status: 400 })
  }

  const currentLanguage = request.cookies.get(SHARED_LANGUAGE_COOKIE)?.value
  if (isValidLanguage(currentLanguage)) return NextResponse.next()

  const language = detectFromAcceptLanguage(request.headers.get('accept-language'))
  const requestHeaders = new Headers(request.headers)
  const existingCookies = request.headers.get('cookie') ?? ''
  const languageCookie = `${SHARED_LANGUAGE_COOKIE}=${language}`
  requestHeaders.set('cookie', existingCookies ? `${existingCookies}; ${languageCookie}` : languageCookie)

  const response = NextResponse.next({ request: { headers: requestHeaders } })
  response.cookies.set(SHARED_LANGUAGE_COOKIE, language, {
    maxAge: 365 * 24 * 60 * 60,
    path: '/',
    sameSite: 'lax',
    secure: process.env.NODE_ENV === 'production',
  })
  return response
}

export const config = {
  matcher: ['/((?!_next/static|_next/image|_next/webpack-hmr|favicon\\.ico|.*\\.(?:png|ico|jpg|jpeg|svg|webp)$).*)'],
}
