import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { updateSession, decrypt } from './lib/auth'

export async function proxy(request: NextRequest) {
  // Always update session expiration
  let response = await updateSession(request)

  const isAuthPage = request.nextUrl.pathname.startsWith('/admin/login')
  const isAdminPage = request.nextUrl.pathname.startsWith('/admin')

  // Check if session exists and is valid
  const sessionValue = request.cookies.get('session')?.value
  let session = null
  if (sessionValue) {
    try {
      session = await decrypt(sessionValue)
    } catch(e) {
      session = null
    }
  }

  // If trying to access admin pages (except login) without a valid session
  if (isAdminPage && !isAuthPage && !session) {
    return NextResponse.redirect(new URL('/admin/login', request.url))
  }

  // If trying to access login page with a valid session
  if (isAuthPage && session) {
    return NextResponse.redirect(new URL('/admin', request.url))
  }

  return response || NextResponse.next()
}

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