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

const PUBLIC_PATHS = [
  '/login',
  '/api/auth',
  '/api/webhooks',
  '/api/upload',
  // H5 外部用户入口：无 better-auth session，用 forge_h5 cookie + JWT 独立鉴权
  '/h5',
  '/api/h5',
]

function hasSessionCookie(req: NextRequest): boolean {
  return req.cookies.getAll().some((cookie) => cookie.name.includes('better-auth.session_token'))
}

export function middleware(req: NextRequest) {
  const { pathname } = req.nextUrl
  const isPublic = PUBLIC_PATHS.some((path) => pathname === path || pathname.startsWith(`${path}/`))
  const isAsset = pathname.startsWith('/_next/') || pathname.startsWith('/favicon') || pathname.includes('.')

  if (isPublic || isAsset) {
    return NextResponse.next()
  }

  if (!hasSessionCookie(req)) {
    if (pathname.startsWith('/api/')) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }
    const loginUrl = new URL('/login', req.url)
    loginUrl.searchParams.set('returnTo', pathname)
    return NextResponse.redirect(loginUrl)
  }

  return NextResponse.next()
}

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
}
