import { withAuth } from 'next-auth/middleware'
import { NextResponse } from 'next/server'

export default withAuth(
  function middleware(req) {
    const token = req.nextauth.token
    const pathname = req.nextUrl.pathname

    // Admin routes protection
    if (pathname.startsWith('/admin') && token?.role !== 'ADMIN') {
      return NextResponse.redirect(new URL('/auth/login?error=unauthorized', req.url))
    }

    // User dashboard protection
    if (pathname.startsWith('/dashboard') && !token) {
      return NextResponse.redirect(new URL('/auth/login', req.url))
    }

    // Banned user check
    if (token?.isBanned) {
      return NextResponse.redirect(new URL('/auth/banned', req.url))
    }

    return NextResponse.next()
  },
  {
    callbacks: {
      authorized: ({ token, req }) => {
        const pathname = req.nextUrl.pathname
        // Public routes always allowed
        if (
          pathname.startsWith('/api/auth') ||
          pathname.startsWith('/api/payment/webhook') ||
          pathname.startsWith('/api/vip/webhook') ||
          pathname === '/' ||
          pathname.startsWith('/games') ||
          pathname.startsWith('/products') ||
          pathname.startsWith('/check-order') ||
          pathname.startsWith('/auth')
        ) {
          return true
        }
        return !!token
      },
    },
  }
)

export const config = {
  matcher: [
    '/dashboard/:path*',
    '/admin/:path*',
    '/api/orders/:path*',
    '/api/wallet/:path*',
    '/api/admin/:path*',
  ],
}
