import {NextRequest, NextResponse} from 'next/server'
import {refreshAuth} from '@/actions/auth'

export const config = {
  matcher: [
    '/((?!api|_next/static|_next/image|.well-known|sw.js|favicon.ico|sitemap.xml|robots.txt).*(?<!\.svg|\.webp|\.jpg)$)',
  ],
}

export async function proxy(request: NextRequest) {
  console.log('👀 middleware triggered', request.method, request.nextUrl.pathname)

  // 记录请求页面
  request.headers.set('x-pathname', request.nextUrl.pathname)

  // 刷新访问令牌
  try {
    const accessToken = request.cookies.get('auth_token')
    const refreshToken = request.cookies.get('auth_refresh')
    if (!accessToken && !!refreshToken) {
      console.log('💡 refresh token')
      const token = await refreshAuth()
      request.cookies.set('auth_token', token.access_token)
      request.cookies.set('auth_refresh', token.refresh_token)
    }
  }
  catch (e) {
    console.log('刷新访问令牌失败', request.url, (e as Error).message)
  }

  // 验证访问令牌
  const hasToken = !!request.cookies.get('auth_token')
  const isToAdmin = request.nextUrl.pathname.startsWith('/admin')
  if (!hasToken && isToAdmin) {
    return NextResponse.redirect(`${request.nextUrl.origin}/login?redirect=${request.nextUrl.pathname}`)
  }

  return NextResponse.next({request})
}
