import { NextRequest, NextResponse } from 'next/server'
import { jwtVerify } from 'jose'

const PROTECTED = ['/dashboard', '/admin', '/create', '/items/new', '/settings']
const AUTH_PAGES = ['/login', '/signup']

async function getUserFromToken(token: string | undefined){
  if(!token) return null
  try {
    const secret = new TextEncoder().encode(process.env.JWT_SECRET || 'dev_secret_change_me')
    const { payload } = await jwtVerify(token, secret)
    return payload as any
  } catch { return null }
}

export async function middleware(req: NextRequest){
  const token = req.cookies.get('iyjm_token')?.value
  const user = await getUserFromToken(token)
  const path = req.nextUrl.pathname

  const isProtected = PROTECTED.some(p => path.startsWith(p))
  const isAuthPage = AUTH_PAGES.some(p => path.startsWith(p))

  // 1. 보호된 페이지인데 비로그인 → /login?redirect=...
  if(isProtected && !user){
    const url = new URL('/login', req.url)
    url.searchParams.set('redirect', path)
    // alert는 클라이언트에서 처리, 여기선 리다이렉트
    return NextResponse.redirect(url)
  }

  // 2. 이미 로그인했는데 /login,/signup 가면 /dashboard로
  if(isAuthPage && user){
    return NextResponse.redirect(new URL('/dashboard', req.url))
  }

  // 3. /admin 은 level 10만
  if(path.startsWith('/admin') && user){
    if((user.level || 1) < 10){
      return NextResponse.redirect(new URL('/dashboard', req.url))
    }
  }

  return NextResponse.next()
}

export const config = {
  matcher: ['/dashboard/:path*', '/admin/:path*', '/create/:path*', '/login', '/signup', '/items/new/:path*']
}
