import { NextRequest, NextResponse } from 'next/server'
import createMiddleware from 'next-intl/middleware'
import { auth } from '@/lib/auth'
import { routing } from '@/i18n/routing'

const intlMiddleware = createMiddleware(routing)

export const proxy = auth((request) => {
  const isAuthOrAdmin = request.nextUrl.pathname.startsWith('/admin') || request.nextUrl.pathname.startsWith('/login')

  if (request.nextUrl.pathname.startsWith('/admin')) {
    const session = request.auth
    if (!session || (session.user as any)?.role !== 'ADMIN') {
      return NextResponse.redirect(new URL('/login', request.url))
    }
  }

  if (isAuthOrAdmin) {
    return NextResponse.next()
  }

  return intlMiddleware(request)
})

export const config = {
  matcher: ['/((?!api|_next|_vercel|.*\\..*).*)']
}
